

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=dark>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/memory_blog/img/fluid.png">
  <link rel="icon" href="/memory_blog/img/icon/dw.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="Memory">
  <meta name="keywords" content="">
  
    <meta name="description" content="🧃 介绍Python爬虫的进阶技术，包括动态页面爬取、数据解析、反爬虫策略等，并通过实战案例展示其实际应用">
<meta property="og:type" content="article">
<meta property="og:title" content="探索Python爬虫的无限可能性：基础与应用">
<meta property="og:url" content="https://test.atomgit.net/memory_blog/2023/05/21/%E6%8E%A2%E7%B4%A2%20Python%20%E7%88%AC%E8%99%AB%E7%9A%84%E6%97%A0%E9%99%90%E5%8F%AF%E8%83%BD%E6%80%A7%EF%BC%9A%E5%9F%BA%E7%A1%80%E4%B8%8E%E5%BA%94%E7%94%A8/index.html">
<meta property="og:site_name" content="Memory&#39;s blog">
<meta property="og:description" content="🧃 介绍Python爬虫的进阶技术，包括动态页面爬取、数据解析、反爬虫策略等，并通过实战案例展示其实际应用">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://test.atomgit.net/memory_blog/img/artical/tree2.jpg">
<meta property="article:published_time" content="2023-05-21T12:35:01.000Z">
<meta property="article:modified_time" content="2023-12-20T11:26:44.000Z">
<meta property="article:author" content="Memory">
<meta property="article:tag" content="开发经验">
<meta property="article:tag" content="爬虫">
<meta property="article:tag" content="Python">
<meta property="article:tag" content="数据处理">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://test.atomgit.net/memory_blog/img/artical/tree2.jpg">
  
  
  
  <title>探索Python爬虫的无限可能性：基础与应用 - Memory&#39;s blog</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/memory_blog/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/memory_blog/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/memory_blog/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"test.atomgit.net","root":"/memory_blog/","version":"1.9.4","typing":{"enable":true,"typeSpeed":100,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":false,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":true,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/memory_blog/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/memory_blog/js/utils.js" ></script>
  <script  src="/memory_blog/js/color-schema.js" ></script>
  

  

  

  

  

  

  

  



  
<meta name="generator" content="Hexo 5.4.2"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 75vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/memory_blog/">
      <strong>Memory&#39;s blog</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/memory_blog/">
                <i class="iconfont icon-home-fill"></i>
                <span>首页</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/memory_blog/archives/">
                <i class="iconfont icon-archive-fill"></i>
                <span>归档</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/memory_blog/categories/">
                <i class="iconfont icon-category-fill"></i>
                <span>分类</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/memory_blog/tags/">
                <i class="iconfont icon-tags-fill"></i>
                <span>标签</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/memory_blog/about/">
                <i class="iconfont icon-user-fill"></i>
                <span>关于</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/memory_blog/links/">
                <i class="iconfont icon-link-fill"></i>
                <span>友链</span>
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              <i class="iconfont icon-search"></i>
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">
              <i class="iconfont icon-dark" id="color-toggle-icon"></i>
            </a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/memory_blog/img/newBG/girl.jpg') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="探索Python爬虫的无限可能性：基础与应用"></span>
          
        </div>

        
          
  <div class="mt-3">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-author" aria-hidden="true"></i>
        Memory
      </span>
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2023-05-21 20:35" pubdate>
          2023年5月21日 晚上
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          42k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          105 分钟
        
      </span>
    

    
    
      
        <span id="leancloud-page-views-container" class="post-meta" style="display: none">
          <i class="iconfont icon-eye" aria-hidden="true"></i>
          <span id="leancloud-page-views"></span> 次
        </span>
        
      
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar category-bar" style="margin-right: -1rem">
    





<div class="category-list">
  
  
    
    
    
    <div class="category row nomargin-x">
      <a class="category-item 
          list-group-item category-item-action col-10 col-md-11 col-xm-11" title="Python"
        id="heading-a7f5f35426b927411fc9231b56382173" role="tab" data-toggle="collapse" href="#collapse-a7f5f35426b927411fc9231b56382173"
        aria-expanded="true"
      >
        Python
        <span class="list-group-count">(1)</span>
        <i class="iconfont icon-arrowright"></i>
      </a>
      
      <div class="category-collapse collapse show" id="collapse-a7f5f35426b927411fc9231b56382173"
           role="tabpanel" aria-labelledby="heading-a7f5f35426b927411fc9231b56382173">
        
        
          
          
  <div class="category-post-list">
    
    
  </div>

          
  
    
    
    
    <div class="category-sub row nomargin-x">
      <a class="category-subitem 
          list-group-item category-item-action col-10 col-md-11 col-xm-11" title="爬虫"
        id="heading-fdd054bd223cceafd35557bacefeb7ae" role="tab" data-toggle="collapse" href="#collapse-fdd054bd223cceafd35557bacefeb7ae"
        aria-expanded="true"
      >
        爬虫
        <span class="list-group-count">(1)</span>
        <i class="iconfont icon-arrowright"></i>
      </a>
      
      <div class="category-collapse collapse show" id="collapse-fdd054bd223cceafd35557bacefeb7ae"
           role="tabpanel" aria-labelledby="heading-fdd054bd223cceafd35557bacefeb7ae">
        
        
          
          
  <div class="category-post-list">
    
    
  </div>

          
  
    
    
    
    <div class="category-sub row nomargin-x">
      <a class="category-subitem 
          list-group-item category-item-action col-10 col-md-11 col-xm-11" title="数据处理"
        id="heading-cfc089f7d2c4bd1de60b70fd7f8fd40a" role="tab" data-toggle="collapse" href="#collapse-cfc089f7d2c4bd1de60b70fd7f8fd40a"
        aria-expanded="true"
      >
        数据处理
        <span class="list-group-count">(1)</span>
        <i class="iconfont icon-arrowright"></i>
      </a>
      
      <div class="category-collapse collapse show" id="collapse-cfc089f7d2c4bd1de60b70fd7f8fd40a"
           role="tabpanel" aria-labelledby="heading-cfc089f7d2c4bd1de60b70fd7f8fd40a">
        
        
          
  <div class="category-post-list">
    
    
      
      
        <a href="/memory_blog/2023/05/21/%E6%8E%A2%E7%B4%A2%20Python%20%E7%88%AC%E8%99%AB%E7%9A%84%E6%97%A0%E9%99%90%E5%8F%AF%E8%83%BD%E6%80%A7%EF%BC%9A%E5%9F%BA%E7%A1%80%E4%B8%8E%E5%BA%94%E7%94%A8/" title="探索Python爬虫的无限可能性：基础与应用"
           class="list-group-item list-group-item-action
           active">
          <span class="category-post">探索Python爬虫的无限可能性：基础与应用</span>
        </a>
      
    
  </div>

        
      </div>
    </div>
  
        
      </div>
    </div>
  
        
      </div>
    </div>
  
</div>


  </aside>


    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">探索Python爬虫的无限可能性：基础与应用</h1>
            
              <p class="note note-success">
                
                  
                    本文最后更新于：7 个月前
                  
                
              </p>
            
            
              <div class="markdown-body">
                
                <h1 id="破冰"><a href="#破冰" class="headerlink" title="破冰"></a>破冰</h1><blockquote>
<h4 id="一些废话"><a href="#一些废话" class="headerlink" title="一些废话"></a>一些废话</h4><p>🥣 这学期学校开设了 <strong>Python 课程</strong>，我索性把<strong>课堂作业</strong>啥的都放在这个栏目下了，那么这篇博客就用来<strong>记录日常的 Python 学习经验</strong>吧</p>
<p>🍝 这篇<strong>博客原标题</strong>是：</p>
<ul>
<li><code>探索Python爬虫的无限可能性：基础与应用</code></li>
<li><code>介绍Python爬虫的进阶技术，包括动态页面爬取、数据解析、反爬虫策略等，并通过实战案例展示其实际应用</code></li>
</ul>
<p>感觉这篇博文改名也没多大必要，不过还是把原标题放这留个纪念<strong>（2023/11/09晚）</strong></p>
</blockquote>
<h1 id="正文"><a href="#正文" class="headerlink" title="正文"></a>正文</h1><h2 id="Python爬虫学习"><a href="#Python爬虫学习" class="headerlink" title="Python爬虫学习"></a>Python爬虫学习</h2><ul>
<li><h5 id="一直以来都想学习爬虫技术-却一直下不了决心-不知道从何学起-也没有精力去学"><a href="#一直以来都想学习爬虫技术-却一直下不了决心-不知道从何学起-也没有精力去学" class="headerlink" title="一直以来都想学习爬虫技术, 却一直下不了决心, 不知道从何学起, 也没有精力去学"></a>一直以来都想学习爬虫技术, 却一直下不了决心, 不知道从何学起, 也没有精力去学</h5></li>
<li><h5 id="过年前后-看过了黑马的Python基础课-掌握了基本的语法-现在伙伴匹配系统基础功能也完成了-可以拿时间来系统且快速地学习Python爬虫了-主要是我觉得一个Java程序猿怎么能不懂爬虫呢"><a href="#过年前后-看过了黑马的Python基础课-掌握了基本的语法-现在伙伴匹配系统基础功能也完成了-可以拿时间来系统且快速地学习Python爬虫了-主要是我觉得一个Java程序猿怎么能不懂爬虫呢" class="headerlink" title="过年前后, 看过了黑马的Python基础课, 掌握了基本的语法, 现在伙伴匹配系统基础功能也完成了, 可以拿时间来系统且快速地学习Python爬虫了, 主要是我觉得一个Java程序猿怎么能不懂爬虫呢"></a>过年前后, 看过了黑马的Python基础课, 掌握了基本的语法, 现在伙伴匹配系统基础功能也完成了, 可以拿时间来系统且快速地学习Python爬虫了, 主要是我觉得一个Java程序猿怎么能不懂爬虫呢</h5></li>
</ul>
<h3 id="爬虫的分类"><a href="#爬虫的分类" class="headerlink" title="爬虫的分类"></a>爬虫的分类</h3><ul>
<li><h5 id="API爬虫和网页爬虫（2023-08-29晚）"><a href="#API爬虫和网页爬虫（2023-08-29晚）" class="headerlink" title="API爬虫和网页爬虫（2023/08/29晚）"></a>API爬虫和网页爬虫（2023/08/29晚）</h5></li>
</ul>
<figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs css">当从更专业的角度讨论API爬虫和网页爬虫时，我们可以更详细地了解它们的定义、特点和用途。<br><br>API爬虫是指通过调用网络应用程序接口（API）来获取数据的爬虫。API是一种允许不同应用程序之间进行通信和交互的接口。API通常提供了固定的数据格式和结构，比如JSON或XML，这使得数据更易于获取和解析。API爬虫通过发送HTTP请求到API的URL路径，来获取数据。一旦数据返回，爬虫可以解析它，并对数据进行处理和分析。<br><br>API爬虫的优点在于，它可以更方便地获取和处理结构化的数据，因为API通常提供了规范化的数据格式。此外，由于API接口具有稳定性和可靠性，爬取数据的稳定性和准确性也相对较高。因此，API 爬虫通常被用于从特定网站、应用程序或服务中获取数据。<br><br>网页爬虫则是通过发送HTTP请求到网页的URL路径，获取返回的<span class="hljs-selector-tag">HTML</span>页面源代码，并进行解析、提取和处理信息的工具。网页爬虫通常用于从网页中获取结构化和非结构化的数据。它们可以通过解析<span class="hljs-selector-tag">HTML</span>文档中的标签、属性和内容，来获取所需的数据。网页爬虫的输出可以是包含所提取数据的结构化文本文件或数据库。<br><br>网页爬虫的优点在于其灵活性和适用范围广泛。它们可以适应不同类型的网页，不仅限于特定的API接口。网页爬虫可以用于各种不同的应用，如搜索引擎索引、产品信息收集、舆情分析等。<br><br>总之，API爬虫和网页爬虫是两种不同的爬虫类型，它们在采集数据的方式、解析数据的方法和适用范围上存在差异。根据需求和情境，选择合适的爬虫类型可以提高爬取数据的效率和准确性。<br><br>希望这个更专业的解释对你有帮助！如果还有其他问题，请随时提问。<br></code></pre></td></tr></table></figure>

<h3 id="Day1"><a href="#Day1" class="headerlink" title="Day1"></a>Day1</h3><ul>
<li><h5 id="今天是学习的第一天-学习爬虫过程中也了解到了不少计网的知识-这令我很惊喜了"><a href="#今天是学习的第一天-学习爬虫过程中也了解到了不少计网的知识-这令我很惊喜了" class="headerlink" title="今天是学习的第一天, 学习爬虫过程中也了解到了不少计网的知识, 这令我很惊喜了"></a>今天是学习的第一天, 学习爬虫过程中也了解到了不少计网的知识, 这令我很惊喜了</h5></li>
<li><h5 id="简要总结一下学到些什么吧-详细的知识点可以拿到老师的-待会儿可以贴上来-我就记重点了"><a href="#简要总结一下学到些什么吧-详细的知识点可以拿到老师的-待会儿可以贴上来-我就记重点了" class="headerlink" title="简要总结一下学到些什么吧, 详细的知识点可以拿到老师的, 待会儿可以贴上来, 我就记重点了"></a>简要总结一下学到些什么吧, 详细的知识点可以拿到老师的, 待会儿可以贴上来, 我就记重点了</h5></li>
<li><h5 id="requests-http-https协议-爬虫-XML-XHR-AJAX-axios-这是我今天了解到的概念"><a href="#requests-http-https协议-爬虫-XML-XHR-AJAX-axios-这是我今天了解到的概念" class="headerlink" title="requests, http/https协议, 爬虫, XML, XHR, AJAX, axios  这是我今天了解到的概念"></a>requests, http/https协议, 爬虫, XML, XHR, AJAX, axios  这是我今天了解到的概念</h5></li>
<li><h5 id="爬取步骤"><a href="#爬取步骤" class="headerlink" title="爬取步骤"></a>爬取步骤</h5></li>
</ul>
<figure class="highlight markdown"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs markdown">-- url请求路径<br>-- UA伪装<br>-- 请求参数<br>-- 发送请求<br>-- 接收响应值<br>-- 持久化数据<br></code></pre></td></tr></table></figure>

<ul>
<li><h5 id="今天爬取到了搜狗网页-百度翻译-iTab标签页-还是有很多注意点的-把代码扔这吧"><a href="#今天爬取到了搜狗网页-百度翻译-iTab标签页-还是有很多注意点的-把代码扔这吧" class="headerlink" title="今天爬取到了搜狗网页 百度翻译 iTab标签页 还是有很多注意点的, 把代码扔这吧"></a>今天爬取到了搜狗网页 百度翻译 iTab标签页 还是有很多注意点的, 把代码扔这吧</h5></li>
<li><h5 id="搜狗网页采集"><a href="#搜狗网页采集" class="headerlink" title="搜狗网页采集"></a>搜狗网页采集</h5></li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">import</span> requests<br><br><span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">&#x27;__main__&#x27;</span>:<br>    <span class="hljs-comment"># UA伪装: 爬虫对应的身份标识伪装成某一浏览器, 避免请求被拒绝</span><br>    headers = &#123;<br>        <span class="hljs-string">&#x27;User-Agent&#x27;</span>: <span class="hljs-string">&#x27;Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1 Edg/113.0.0.0&#x27;</span><br>    &#125;<br>    <span class="hljs-comment"># 请求路径</span><br>    url = <span class="hljs-string">&#x27;https://www.sogou.com/web?&#x27;</span><br>    <span class="hljs-comment"># 请求参数</span><br>    content = <span class="hljs-built_in">input</span>(<span class="hljs-string">&#x27;输入搜索词:&#x27;</span>)<br>    params = &#123;<br>        <span class="hljs-string">&#x27;query&#x27;</span>: content<br>    &#125;<br>    <span class="hljs-comment"># 发送请求</span><br>    response = requests.get(url=url, params=params, headers=headers)<br>    <span class="hljs-comment"># 获取响应值</span><br>    page_text = response.text<br>    <span class="hljs-comment"># 持久化存储</span><br>    fileName = content + <span class="hljs-string">&#x27;.html&#x27;</span><br>    <span class="hljs-keyword">with</span> <span class="hljs-built_in">open</span>(fileName, <span class="hljs-string">&#x27;w&#x27;</span>, encoding=<span class="hljs-string">&#x27;utf-8&#x27;</span>) <span class="hljs-keyword">as</span> fp:<br>        fp.write(page_text)<br>    <span class="hljs-built_in">print</span>(fileName, <span class="hljs-string">&#x27;抓取成功!&#x27;</span>)<br><br></code></pre></td></tr></table></figure>

<ul>
<li><h5 id="百度翻译爬取"><a href="#百度翻译爬取" class="headerlink" title="百度翻译爬取"></a>百度翻译爬取</h5></li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">import</span> json<br><br><span class="hljs-keyword">import</span> requests<br><br><span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">&#x27;__main__&#x27;</span>:<br>    <span class="hljs-comment"># url路径</span><br>    url = <span class="hljs-string">&quot;https://fanyi.baidu.com/sug&quot;</span><br>    <span class="hljs-comment"># UA伪装</span><br>    headers = &#123;<br>        <span class="hljs-string">&#x27;User-Agent&#x27;</span>: <span class="hljs-string">&#x27;Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1 Edg/113.0.0.0&#x27;</span><br>    &#125;<br>    <span class="hljs-comment"># 请求参数</span><br>    content = <span class="hljs-built_in">input</span>(<span class="hljs-string">&#x27;输入要翻译的词:&#x27;</span>)<br>    data = &#123;<br>        <span class="hljs-string">&#x27;kw&#x27;</span>: content<br>    &#125;<br>    <span class="hljs-comment"># 发送请求</span><br>    response = requests.post(url=url, data=data, headers=headers)<br>    <span class="hljs-comment"># 获取响应</span><br>    dic_obj = response.json()<br>    <span class="hljs-comment"># 持久化存储</span><br>    filename = content + <span class="hljs-string">&#x27;.json&#x27;</span><br>    fp = <span class="hljs-built_in">open</span>(filename, <span class="hljs-string">&#x27;w&#x27;</span>, encoding=<span class="hljs-string">&#x27;utf-8&#x27;</span>)<br>    json.dump(dic_obj, fp, ensure_ascii=<span class="hljs-literal">False</span>)<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&#x27;over!!!&#x27;</span>)<br><br></code></pre></td></tr></table></figure>

<ul>
<li><h5 id="iTab标签页爬取"><a href="#iTab标签页爬取" class="headerlink" title="iTab标签页爬取"></a>iTab标签页爬取</h5></li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">import</span> json<br><br><span class="hljs-keyword">import</span> requests<br><span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">&#x27;__main__&#x27;</span>:<br>    <span class="hljs-comment"># url路径</span><br>    url = <span class="hljs-string">&quot;https://api.codelife.cc/api/getWeather&quot;</span><br>    <span class="hljs-comment"># UA伪装</span><br>    headers = &#123;<br>        <span class="hljs-string">&#x27;User-Agent&#x27;</span>: <span class="hljs-string">&#x27;Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1 Edg/113.0.0.0&#x27;</span><br>    &#125;<br>    <span class="hljs-comment"># 请求参数</span><br>    params = &#123;<br>        <span class="hljs-string">&#x27;lang&#x27;</span>: <span class="hljs-string">&#x27; cn&#x27;</span>,<br>        <span class="hljs-string">&#x27;location&#x27;</span>: <span class="hljs-string">&#x27;101101101&#x27;</span><br>    &#125;<br>    <span class="hljs-comment"># 发送请求</span><br>    response = requests.get(url, params=params, headers=headers)<br>    <span class="hljs-comment"># 获取响应</span><br>    dic_obj = response.json()<br>    <span class="hljs-comment"># 持久化存储</span><br>    fp = <span class="hljs-built_in">open</span>(<span class="hljs-string">&#x27;iTab标签页.json&#x27;</span>, <span class="hljs-string">&#x27;w&#x27;</span>, encoding=<span class="hljs-string">&#x27;utf-8&#x27;</span>)<br>    json.dump(dic_obj, fp, ensure_ascii=<span class="hljs-literal">False</span>)<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&#x27;over!!!&#x27;</span>)<br></code></pre></td></tr></table></figure>

<h3 id="Day2"><a href="#Day2" class="headerlink" title="Day2"></a>Day2</h3><ul>
<li><h5 id="距离上次学习都他妈过去5天了"><a href="#距离上次学习都他妈过去5天了" class="headerlink" title="距离上次学习都他妈过去5天了"></a>距离上次学习都他妈过去5天了</h5></li>
<li><h5 id="交一下昨天的作业吧-比较复杂的爬取"><a href="#交一下昨天的作业吧-比较复杂的爬取" class="headerlink" title="交一下昨天的作业吧  比较复杂的爬取"></a>交一下昨天的作业吧  比较复杂的爬取</h5></li>
<li><h5 id="化妆品生产许可信息"><a href="#化妆品生产许可信息" class="headerlink" title="化妆品生产许可信息"></a>化妆品生产许可信息</h5></li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">import</span> requests<br><span class="hljs-keyword">import</span> json<br><br>id_list = []  <span class="hljs-comment"># 获取每个企业的id</span><br><span class="hljs-comment"># UA伪装</span><br>headers = &#123;<br>    <span class="hljs-string">&#x27;User-Agent&#x27;</span>: <span class="hljs-string">&#x27;Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) &#x27;</span><br>                  <span class="hljs-string">&#x27;Chrome/88.0.4324.182 Safari/537.36 Edg/88.0.705.74&#x27;</span><br>&#125;<br><span class="hljs-comment"># url请求路径</span><br>url = <span class="hljs-string">&#x27;http://scxk.nmpa.gov.cn:81/xk/itownet/portalAction.do?method=getXkzsList&#x27;</span><br><span class="hljs-comment"># 发送请求</span><br><span class="hljs-comment"># 拿取 1-19 页</span><br><span class="hljs-keyword">for</span> page <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-number">1</span>, <span class="hljs-number">20</span>):<br>    page = <span class="hljs-built_in">str</span>(page)<br>    <span class="hljs-comment"># 请求参数</span><br>    data = &#123;<br>        <span class="hljs-string">&#x27;on&#x27;</span>: <span class="hljs-string">&#x27;true&#x27;</span>,<br>        <span class="hljs-string">&#x27;page&#x27;</span>: page,<br>        <span class="hljs-string">&#x27;pageSize&#x27;</span>: <span class="hljs-string">&#x27;15&#x27;</span>,<br>        <span class="hljs-string">&#x27;productName&#x27;</span>: <span class="hljs-string">&#x27;&#x27;</span>,<br>        <span class="hljs-string">&#x27;conditionType&#x27;</span>: <span class="hljs-string">&#x27;1&#x27;</span>,<br>        <span class="hljs-string">&#x27;applyname&#x27;</span>: <span class="hljs-string">&#x27;&#x27;</span>,<br>        <span class="hljs-string">&#x27;applysn&#x27;</span>: <span class="hljs-string">&#x27;&#x27;</span><br>    &#125;<br>    <span class="hljs-comment"># 以json的格式返回response的内容（如果有的话）</span><br>    response = requests.post(url=url, headers=headers, data=data).json()<br>    <span class="hljs-keyword">for</span> dic <span class="hljs-keyword">in</span> response[<span class="hljs-string">&#x27;list&#x27;</span>]:  <span class="hljs-comment"># response是一个字典，list是一个键，而我们需要这个键对应的值，所以就有了`response[&#x27;list&#x27;],</span><br>        <span class="hljs-comment"># 稍微复杂的是dic是一个数组，这个数组里包括了一部字典，</span><br>        id_list.append(dic[<span class="hljs-string">&#x27;ID&#x27;</span>])  <span class="hljs-comment"># dic是一个字典，我们同样用‘ID’这个键访问它对应的值，并把这个值添加到id_list[]里</span><br><br><span class="hljs-comment"># 从这里开始整个程序分为两部分，上面是获取所有的id，下面是对所有的id信息进行请求，然后是保存。</span><br>all_data = []  <span class="hljs-comment"># 这个列表用来存放最终的所有公司的具体信息</span><br><span class="hljs-comment"># url请求路径</span><br>post_url = <span class="hljs-string">&#x27;http://scxk.nmpa.gov.cn:81/xk/itownet/portalAction.do?method=getXkzsById&#x27;</span><br><span class="hljs-comment"># 发送请求</span><br><span class="hljs-keyword">for</span> <span class="hljs-built_in">id</span> <span class="hljs-keyword">in</span> id_list:  <span class="hljs-comment"># 把id封装到字典当作作为参数以备调用</span><br>    <span class="hljs-comment"># 请求参数</span><br>    data2 = &#123;  <span class="hljs-comment"># 遍历所有的id</span><br>        <span class="hljs-string">&#x27;id&#x27;</span>: <span class="hljs-built_in">id</span><br>    &#125;<br>    result = requests.post(url=post_url, headers=headers, data=data2).json()<br>    all_data.append(result)  <span class="hljs-comment"># 通过a数据解析append方法把所有的请求结果上传到all_data[]中</span><br>    <span class="hljs-built_in">print</span>(result)  <span class="hljs-comment"># 直接输出请求返回的结果</span><br><br><span class="hljs-comment"># 持久化存储</span><br>file = <span class="hljs-built_in">open</span>(<span class="hljs-string">&#x27;./化妆品生产许可信息.json&#x27;</span>, <span class="hljs-string">&#x27;w&#x27;</span>, encoding=<span class="hljs-string">&#x27;utf-8&#x27;</span>)<br>json.dump(all_data, fp=file, ensure_ascii=<span class="hljs-literal">False</span>)<br><br></code></pre></td></tr></table></figure>

<ul>
<li><h5 id="今天又学习了图片的爬取-再补个作业"><a href="#今天又学习了图片的爬取-再补个作业" class="headerlink" title="今天又学习了图片的爬取 再补个作业"></a>今天又学习了图片的爬取 再补个作业</h5></li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">import</span> os.path<br><span class="hljs-keyword">import</span> re<br><span class="hljs-keyword">import</span> requests<br><br><span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">&#x27;__main__&#x27;</span>:<br>    <span class="hljs-comment"># 创建文件夹</span><br>    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> os.path.exists(<span class="hljs-string">&#x27;./imgs&#x27;</span>):<br>        os.mkdir(<span class="hljs-string">&#x27;./imgs&#x27;</span>)<br>    <span class="hljs-comment"># 请求路径</span><br>    url = <span class="hljs-string">&#x27;https://www.woyaogexing.com/tupian/index_4.html&#x27;</span><br>    <span class="hljs-comment"># UA伪装</span><br>    headers = &#123;<br>        <span class="hljs-string">&#x27;User-Agent&#x27;</span>: <span class="hljs-string">&#x27;Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, &#x27;</span><br>                      <span class="hljs-string">&#x27;like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1 Edg/113.0.0.0&#x27;</span><br>    &#125;<br>    <span class="hljs-comment"># 爬取对应的网页内容</span><br>    page_text = requests.get(url=url, headers=headers).text<br>    <span class="hljs-comment"># print(page_text)</span><br>    <span class="hljs-comment"># 爬取对应网页上的图片(正则表达式)</span><br>    <span class="hljs-comment"># 编写正则表达式</span><br>    ex = <span class="hljs-string">&#x27;&lt;div class=&quot;txList &quot;&gt;.*?&lt;img.*?src=&quot;(.*?)&quot;.*?&gt;.*?&lt;/div&gt;&#x27;</span><br>    <span class="hljs-comment"># 获取所需字符串</span><br>    img_src_list = re.findall(ex, page_text, re.S)<br>    <span class="hljs-built_in">print</span>(img_src_list)<br>    <span class="hljs-keyword">for</span> img_src <span class="hljs-keyword">in</span> img_src_list:<br>        <span class="hljs-comment"># 拼接完整的图片路径</span><br>        img_src = <span class="hljs-string">&#x27;http:&#x27;</span> + img_src<br>        <span class="hljs-built_in">print</span>(img_src)<br>        <span class="hljs-comment"># 请求图片</span><br>        img = requests.get(url=img_src, headers=headers).content<br>        <span class="hljs-comment"># 图片名</span><br>        img_name = img_src.split(<span class="hljs-string">&#x27;/&#x27;</span>)[-<span class="hljs-number">1</span>]<br>        <span class="hljs-comment"># 图片保存路径</span><br>        img_path = <span class="hljs-string">&#x27;./imgs/&#x27;</span> + img_name<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&#x27;img_path = &#x27;</span> + img_path)<br>        <span class="hljs-comment"># 保存图片</span><br>        <span class="hljs-keyword">with</span> <span class="hljs-built_in">open</span>(img_path, <span class="hljs-string">&#x27;wb&#x27;</span>) <span class="hljs-keyword">as</span> fp:<br>            fp.write(img)<br>        <span class="hljs-built_in">print</span>(img_name + <span class="hljs-string">&#x27;下载完成！&#x27;</span>)<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&#x27;over!!!&#x27;</span>)<br><br></code></pre></td></tr></table></figure>

<ul>
<li><h5 id="这里是使用了正则表达式来处理要爬取的部分数据-我要爬取的图片就是这样的："><a href="#这里是使用了正则表达式来处理要爬取的部分数据-我要爬取的图片就是这样的：" class="headerlink" title="这里是使用了正则表达式来处理要爬取的部分数据 我要爬取的图片就是这样的："></a>这里是使用了正则表达式来处理要爬取的部分数据 我要爬取的图片就是这样的：</h5></li>
</ul>
<p><img src="C:\Users\Lenovo\AppData\Roaming\Typora\typora-user-images\image-20230526151919628.png" alt="image-20230526151919628"></p>
<ul>
<li><h5 id="照猫画虎写了个贪婪匹配（学过都忘了，非常滴不熟练）"><a href="#照猫画虎写了个贪婪匹配（学过都忘了，非常滴不熟练）" class="headerlink" title="照猫画虎写了个贪婪匹配（学过都忘了，非常滴不熟练）"></a>照猫画虎写了个贪婪匹配（学过都忘了，非常滴不熟练）</h5></li>
<li><h5 id="可以爬取多个页面了"><a href="#可以爬取多个页面了" class="headerlink" title="可以爬取多个页面了"></a>可以爬取多个页面了</h5></li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">import</span> os.path<br><span class="hljs-keyword">import</span> re<br><br><span class="hljs-keyword">import</span> requests<br><br><span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">&#x27;__main__&#x27;</span>:<br>    <span class="hljs-comment"># 创建文件夹</span><br>    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> os.path.exists(<span class="hljs-string">&#x27;./imgs&#x27;</span>):<br>        os.mkdir(<span class="hljs-string">&#x27;./imgs&#x27;</span>)<br>    <span class="hljs-comment"># 请求路径</span><br>    url = <span class="hljs-string">&#x27;https://www.woyaogexing.com/tupian/index_%d.html&#x27;</span><br>    <span class="hljs-comment"># UA伪装</span><br>    headers = &#123;<br>        <span class="hljs-string">&#x27;User-Agent&#x27;</span>: <span class="hljs-string">&#x27;Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, &#x27;</span><br>                      <span class="hljs-string">&#x27;like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1 Edg/113.0.0.0&#x27;</span><br>    &#125;<br>    <span class="hljs-keyword">for</span> page_num <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-number">1</span>, <span class="hljs-number">11</span>):<br>        new_url = <span class="hljs-built_in">format</span>(url % page_num)<br>        <span class="hljs-comment"># 爬取对应的网页内容</span><br>        page_text = requests.get(url=new_url, headers=headers).text<br>        <span class="hljs-comment"># print(page_text)</span><br>        <span class="hljs-comment"># 爬取对应网页上的图片(正则表达式)</span><br>        <span class="hljs-comment"># 编写正则表达式</span><br>        ex = <span class="hljs-string">&#x27;&lt;div class=&quot;txList &quot;&gt;.*?&lt;img.*?src=&quot;(.*?)&quot;.*?&gt;.*?&lt;/div&gt;&#x27;</span><br>        <span class="hljs-comment"># 获取所需字符串</span><br>        img_src_list = re.findall(ex, page_text, re.S)<br>        <span class="hljs-built_in">print</span>(img_src_list)<br>        <span class="hljs-keyword">for</span> img_src <span class="hljs-keyword">in</span> img_src_list:<br>            <span class="hljs-comment"># 拼接完整的图片路径</span><br>            img_src = <span class="hljs-string">&#x27;http:&#x27;</span> + img_src<br>            <span class="hljs-built_in">print</span>(img_src)<br>            <span class="hljs-comment"># 请求图片</span><br>            img = requests.get(url=img_src, headers=headers).content<br>            <span class="hljs-comment"># 图片名</span><br>            img_name = img_src.split(<span class="hljs-string">&#x27;/&#x27;</span>)[-<span class="hljs-number">1</span>]<br>            <span class="hljs-comment"># 图片保存路径</span><br>            img_path = <span class="hljs-string">&#x27;./imgs/&#x27;</span> + img_name<br>            <span class="hljs-built_in">print</span>(<span class="hljs-string">&#x27;img_path = &#x27;</span> + img_path)<br>            <span class="hljs-comment"># 保存图片</span><br>            <span class="hljs-keyword">with</span> <span class="hljs-built_in">open</span>(img_path, <span class="hljs-string">&#x27;wb&#x27;</span>) <span class="hljs-keyword">as</span> fp:<br>                fp.write(img)<br>            <span class="hljs-built_in">print</span>(img_name + <span class="hljs-string">&#x27;下载完成！&#x27;</span>)<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&#x27;over!!!&#x27;</span>)<br></code></pre></td></tr></table></figure>

<h3 id="Day3"><a href="#Day3" class="headerlink" title="Day3"></a>Day3</h3><ul>
<li><h5 id="数据分析，爬取页面中标签中的数据"><a href="#数据分析，爬取页面中标签中的数据" class="headerlink" title="数据分析，爬取页面中标签中的数据"></a>数据分析，爬取页面中标签中的数据</h5></li>
<li><h5 id="这边做完几个课堂练习后，自行找了个网页，练习了下："><a href="#这边做完几个课堂练习后，自行找了个网页，练习了下：" class="headerlink" title="这边做完几个课堂练习后，自行找了个网页，练习了下："></a>这边做完几个课堂练习后，自行找了个网页，练习了下：</h5></li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">import</span> os.path<br><br><span class="hljs-keyword">import</span> requests<br><span class="hljs-keyword">from</span> lxml <span class="hljs-keyword">import</span> etree<br><br><span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">&#x27;__main__&#x27;</span>:<br>    <span class="hljs-comment"># url路径</span><br>    url = <span class="hljs-string">&#x27;https://bobopic.com/4kbizhi.html&#x27;</span><br>    <span class="hljs-comment"># UA伪装</span><br>    headers = &#123;<br>        <span class="hljs-string">&#x27;User-Agent&#x27;</span>: <span class="hljs-string">&#x27;Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) &#x27;</span><br>                      <span class="hljs-string">&#x27;Chrome/72.0.3626.121 Safari/537.36&#x27;</span><br>    &#125;<br>    <span class="hljs-comment"># 请求页面</span><br>    page_text = requests.get(url=url, headers=headers).text<br>    <span class="hljs-comment"># 封装页面对象</span><br>    tree = etree.HTML(page_text)<br>    <span class="hljs-comment"># 获取a标签</span><br>    a_list = tree.xpath(<span class="hljs-string">&#x27;//div[@class=&quot;related&quot;]/ul/li/a&#x27;</span>)<br>    <span class="hljs-comment"># 遍历a_list</span><br>    <span class="hljs-keyword">for</span> a <span class="hljs-keyword">in</span> a_list:<br>        <span class="hljs-comment"># 拿取每个a的href</span><br>        a_href = a.xpath(<span class="hljs-string">&#x27;./@href&#x27;</span>)[<span class="hljs-number">0</span>]<br>        <span class="hljs-comment"># 请求新页面</span><br>        new_page_text = requests.get(url=a_href + <span class="hljs-string">&#x27;&#x27;</span>, headers=headers).content<br>        <span class="hljs-comment"># 封装页面对象</span><br>        tree = etree.HTML(new_page_text)<br>        img_list = tree.xpath(<span class="hljs-string">&#x27;//div[@class=&quot;entry-content u-clearfix&quot;]//img&#x27;</span>)<br>        <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> os.path.exists(<span class="hljs-string">&#x27;./二次元风景4k&#x27;</span>):<br>            os.mkdir(<span class="hljs-string">&#x27;./二次元风景4k&#x27;</span>)<br>        <span class="hljs-comment"># 获取新页面下的图片</span><br>        <span class="hljs-keyword">for</span> img <span class="hljs-keyword">in</span> img_list:<br>            <span class="hljs-comment"># 图片名</span><br>            img_name = img.xpath(<span class="hljs-string">&#x27;./@alt&#x27;</span>)[<span class="hljs-number">0</span>] + <span class="hljs-string">&#x27;.jpg&#x27;</span><br>            <span class="hljs-comment"># 图片路径</span><br>            img_src = img.xpath(<span class="hljs-string">&#x27;./@src&#x27;</span>)[<span class="hljs-number">0</span>] + <span class="hljs-string">&#x27;&#x27;</span><br>            <span class="hljs-comment"># 爬取图片</span><br>            img_data = requests.get(url=img_src, headers=headers).content<br>            <span class="hljs-comment"># 图片存放路径</span><br>            img_path = <span class="hljs-string">&#x27;二次元风景4k/&#x27;</span> + img_name<br>            <span class="hljs-comment"># 存放图片</span><br>            <span class="hljs-keyword">with</span> <span class="hljs-built_in">open</span>(<span class="hljs-string">&#x27;二次元风景4k/&#x27;</span> + img_name, <span class="hljs-string">&#x27;wb&#x27;</span>) <span class="hljs-keyword">as</span> fp:<br>                fp.write(img_data)<br>            <span class="hljs-built_in">print</span>(img_name + <span class="hljs-string">&#x27;下载成功！&#x27;</span>)<br><br></code></pre></td></tr></table></figure>

<ul>
<li><h5 id="以alt内容作为图片名，里面含有”-”符号，不能在文件名中出现，搞了老半天（2023-05-30）"><a href="#以alt内容作为图片名，里面含有”-”符号，不能在文件名中出现，搞了老半天（2023-05-30）" class="headerlink" title="以alt内容作为图片名，里面含有”|”符号，不能在文件名中出现，搞了老半天（2023/05/30）"></a>以alt内容作为图片名，里面含有”|”符号，不能在文件名中出现，搞了老半天（2023/05/30）</h5></li>
</ul>
<h2 id="图表绘制"><a href="#图表绘制" class="headerlink" title="图表绘制"></a>图表绘制</h2><ul>
<li>简单记录一下<strong>使用 Python 实现图表绘制</strong>   <strong>（2023/10/16晚）</strong></li>
</ul>
<h3 id="中国版图"><a href="#中国版图" class="headerlink" title="中国版图"></a>中国版图</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">from</span> pyecharts.charts <span class="hljs-keyword">import</span> Map<br><span class="hljs-keyword">from</span> pyecharts <span class="hljs-keyword">import</span> options <span class="hljs-keyword">as</span> opts<br><br><span class="hljs-comment"># 创建地图对象</span><br>china_map = Map()<br><br><span class="hljs-comment"># 准备数据</span><br>province_data = [<br>    (<span class="hljs-string">&quot;广东省&quot;</span>, <span class="hljs-number">100</span>),<br>    (<span class="hljs-string">&quot;北京市&quot;</span>, <span class="hljs-number">506</span>),<br>    (<span class="hljs-string">&quot;上海市&quot;</span>, <span class="hljs-number">88</span>),<br>    (<span class="hljs-string">&quot;山西省&quot;</span>, <span class="hljs-number">1000</span>),<br>    <span class="hljs-comment"># 其他省份数据...</span><br>]<br><br><span class="hljs-comment"># 设置地图数据</span><br>china_map.add(<span class="hljs-string">&quot;中国地图&quot;</span>, province_data, <span class="hljs-string">&quot;china&quot;</span>)<br><br><span class="hljs-comment"># 设置全局选项</span><br>china_map.set_global_opts(<br>    visualmap_opts=opts.VisualMapOpts(<br>        is_show=<span class="hljs-literal">True</span>,<br>        is_piecewise=<span class="hljs-literal">True</span>,<br>        pieces=[<br>            &#123;<span class="hljs-string">&quot;min&quot;</span>: <span class="hljs-number">1</span>, <span class="hljs-string">&quot;max&quot;</span>: <span class="hljs-number">99</span>, <span class="hljs-string">&quot;label&quot;</span>: <span class="hljs-string">&quot;1-99&quot;</span>, <span class="hljs-string">&quot;color&quot;</span>: <span class="hljs-string">&quot;#CCFFFF&quot;</span>&#125;,<br>            &#123;<span class="hljs-string">&quot;min&quot;</span>: <span class="hljs-number">100</span>, <span class="hljs-string">&quot;max&quot;</span>: <span class="hljs-number">500</span>, <span class="hljs-string">&quot;label&quot;</span>: <span class="hljs-string">&quot;100-500&quot;</span>, <span class="hljs-string">&quot;color&quot;</span>: <span class="hljs-string">&quot;#99CCFF&quot;</span>&#125;,<br>            &#123;<span class="hljs-string">&quot;min&quot;</span>: <span class="hljs-number">501</span>, <span class="hljs-string">&quot;max&quot;</span>: <span class="hljs-number">1500</span>, <span class="hljs-string">&quot;label&quot;</span>: <span class="hljs-string">&quot;501-1500&quot;</span>, <span class="hljs-string">&quot;color&quot;</span>: <span class="hljs-string">&quot;#66CCFF&quot;</span>&#125;<br>        ]<br>    )<br>)<br><br><span class="hljs-comment"># 绘图并保存</span><br>china_map.render(<span class="hljs-string">&quot;china_map.html&quot;</span>)<br></code></pre></td></tr></table></figure>

<p><img src="https://gitee.com/deng-2022/pictures/raw/master/images/image-20231016195435508.png" alt="image-20231016195435508"></p>
<h3 id="其他"><a href="#其他" class="headerlink" title="其他"></a>其他</h3><h4 id="折线图"><a href="#折线图" class="headerlink" title="折线图"></a>折线图</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-string">&quot;&quot;&quot;</span><br><span class="hljs-string">演示可视化需求1：折线图开发</span><br><span class="hljs-string">&quot;&quot;&quot;</span><br><span class="hljs-keyword">import</span> json<br><span class="hljs-keyword">from</span> pyecharts.charts <span class="hljs-keyword">import</span> Line<br><span class="hljs-keyword">from</span> pyecharts.options <span class="hljs-keyword">import</span> TitleOpts, LabelOpts<br><br><span class="hljs-comment"># 处理数据</span><br>f_us = <span class="hljs-built_in">open</span>(<span class="hljs-string">&quot;D:/Project/python/other/美国.txt&quot;</span>, <span class="hljs-string">&quot;r&quot;</span>, encoding=<span class="hljs-string">&quot;UTF-8&quot;</span>)<br>us_data = f_us.read()  <span class="hljs-comment"># 美国的全部内容</span><br><br>f_jp = <span class="hljs-built_in">open</span>(<span class="hljs-string">&quot;D:/Project/python/other/日本.txt&quot;</span>, <span class="hljs-string">&quot;r&quot;</span>, encoding=<span class="hljs-string">&quot;UTF-8&quot;</span>)<br>jp_data = f_jp.read()  <span class="hljs-comment"># 日本的全部内容</span><br><br>f_in = <span class="hljs-built_in">open</span>(<span class="hljs-string">&quot;D:/Project/python/other/印度.txt&quot;</span>, <span class="hljs-string">&quot;r&quot;</span>, encoding=<span class="hljs-string">&quot;UTF-8&quot;</span>)<br>in_data = f_in.read()  <span class="hljs-comment"># 印度的全部内容</span><br><br><span class="hljs-comment"># 去掉不合JSON规范的开头</span><br>us_data = us_data.replace(<span class="hljs-string">&quot;jsonp_1629344292311_69436(&quot;</span>, <span class="hljs-string">&quot;&quot;</span>)<br>jp_data = jp_data.replace(<span class="hljs-string">&quot;jsonp_1629350871167_29498(&quot;</span>, <span class="hljs-string">&quot;&quot;</span>)<br>in_data = in_data.replace(<span class="hljs-string">&quot;jsonp_1629350745930_63180(&quot;</span>, <span class="hljs-string">&quot;&quot;</span>)<br><br><span class="hljs-comment"># 去掉不合JSON规范的结尾</span><br>us_data = us_data[:-<span class="hljs-number">2</span>]<br>jp_data = jp_data[:-<span class="hljs-number">2</span>]<br>in_data = in_data[:-<span class="hljs-number">2</span>]<br><br><span class="hljs-comment"># JSON转Python字典</span><br>us_dict = json.loads(us_data)<br>jp_dict = json.loads(jp_data)<br>in_dict = json.loads(in_data)<br><br><span class="hljs-comment"># 获取trend key</span><br>us_trend_data = us_dict[<span class="hljs-string">&#x27;data&#x27;</span>][<span class="hljs-number">0</span>][<span class="hljs-string">&#x27;trend&#x27;</span>]<br>jp_trend_data = jp_dict[<span class="hljs-string">&#x27;data&#x27;</span>][<span class="hljs-number">0</span>][<span class="hljs-string">&#x27;trend&#x27;</span>]<br>in_trend_data = in_dict[<span class="hljs-string">&#x27;data&#x27;</span>][<span class="hljs-number">0</span>][<span class="hljs-string">&#x27;trend&#x27;</span>]<br><br><span class="hljs-comment"># 获取日期数据，用于x轴，取2020年（到 314 下标结束）</span><br>us_x_data = us_trend_data[<span class="hljs-string">&#x27;updateDate&#x27;</span>][:<span class="hljs-number">314</span>]<br>jp_x_data = jp_trend_data[<span class="hljs-string">&#x27;updateDate&#x27;</span>][:<span class="hljs-number">314</span>]<br>in_x_data = in_trend_data[<span class="hljs-string">&#x27;updateDate&#x27;</span>][:<span class="hljs-number">314</span>]<br><br><span class="hljs-comment"># 获取确认数据，用于y轴，取2020年（到 314 下标结束）</span><br>us_y_data = us_trend_data[<span class="hljs-string">&#x27;list&#x27;</span>][<span class="hljs-number">0</span>][<span class="hljs-string">&#x27;data&#x27;</span>][:<span class="hljs-number">314</span>]<br>jp_y_data = jp_trend_data[<span class="hljs-string">&#x27;list&#x27;</span>][<span class="hljs-number">0</span>][<span class="hljs-string">&#x27;data&#x27;</span>][:<span class="hljs-number">314</span>]<br>in_y_data = in_trend_data[<span class="hljs-string">&#x27;list&#x27;</span>][<span class="hljs-number">0</span>][<span class="hljs-string">&#x27;data&#x27;</span>][:<span class="hljs-number">314</span>]<br><br><span class="hljs-comment"># 生成图表</span><br>line = Line()  <span class="hljs-comment"># 构建折线图对象</span><br><span class="hljs-comment"># 添加x轴数据</span><br>line.add_xaxis(us_x_data)  <span class="hljs-comment"># x轴是公用的，所以使用一个国家的数据即可</span><br><span class="hljs-comment"># 添加y轴数据</span><br>line.add_yaxis(<span class="hljs-string">&quot;美国确诊人数&quot;</span>, us_y_data, label_opts=LabelOpts(is_show=<span class="hljs-literal">False</span>))  <span class="hljs-comment"># 添加美国的y轴数据</span><br>line.add_yaxis(<span class="hljs-string">&quot;日本确诊人数&quot;</span>, jp_y_data, label_opts=LabelOpts(is_show=<span class="hljs-literal">False</span>))  <span class="hljs-comment"># 添加日本的y轴数据</span><br>line.add_yaxis(<span class="hljs-string">&quot;印度确诊人数&quot;</span>, in_y_data, label_opts=LabelOpts(is_show=<span class="hljs-literal">False</span>))  <span class="hljs-comment"># 添加印度的y轴数据</span><br><br><span class="hljs-comment"># 设置全局选项</span><br>line.set_global_opts(<br>    <span class="hljs-comment"># 标题设置</span><br>    title_opts=TitleOpts(title=<span class="hljs-string">&quot;2020年美日印三国确诊人数对比折线图&quot;</span>, pos_left=<span class="hljs-string">&quot;center&quot;</span>, pos_bottom=<span class="hljs-string">&quot;1%&quot;</span>)<br>)<br><br><span class="hljs-comment"># 调用render方法，生成图表</span><br>line.render()<br><span class="hljs-comment"># 关闭文件对象</span><br>f_us.close()<br>f_jp.close()<br>f_in.close()<br><br></code></pre></td></tr></table></figure>

<p><img src="https://gitee.com/deng-2022/pictures/raw/master/images/image-20231016194821867.png" alt="image-20231016194821867"></p>
<h4 id="饼图"><a href="#饼图" class="headerlink" title="饼图"></a>饼图</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">from</span> pyecharts.charts <span class="hljs-keyword">import</span> Pie<br><span class="hljs-keyword">from</span> pyecharts <span class="hljs-keyword">import</span> options <span class="hljs-keyword">as</span> opts<br><br><span class="hljs-comment"># 准备饼图数据</span><br>data = [<br>    (<span class="hljs-string">&quot;A&quot;</span>, <span class="hljs-number">30</span>),<br>    (<span class="hljs-string">&quot;B&quot;</span>, <span class="hljs-number">20</span>),<br>    (<span class="hljs-string">&quot;C&quot;</span>, <span class="hljs-number">50</span>)<br>]<br><br><span class="hljs-comment"># 创建饼图对象</span><br>pie = Pie(init_opts=opts.InitOpts(width=<span class="hljs-string">&quot;500px&quot;</span>, height=<span class="hljs-string">&quot;300px&quot;</span>))<br><br><span class="hljs-comment"># 添加数据</span><br>pie.add(<span class="hljs-string">&quot;&quot;</span>, data)<br><br><span class="hljs-comment"># 设置全局选项</span><br>pie.set_global_opts(title_opts=opts.TitleOpts(title=<span class="hljs-string">&quot;饼图示例&quot;</span>))<br><br><span class="hljs-comment"># 绘图并保存</span><br>pie.render(<span class="hljs-string">&quot;pie_chart.html&quot;</span>)<br></code></pre></td></tr></table></figure>

<p><img src="https://gitee.com/deng-2022/pictures/raw/master/images/image-20231016195023196.png" alt="image-20231016195023196"></p>
<h4 id="柱状图"><a href="#柱状图" class="headerlink" title="柱状图"></a>柱状图</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">from</span> pyecharts.charts <span class="hljs-keyword">import</span> Bar<br><span class="hljs-keyword">from</span> pyecharts <span class="hljs-keyword">import</span> options <span class="hljs-keyword">as</span> opts<br><br><span class="hljs-comment"># 准备柱状图数据</span><br>x_data = [<span class="hljs-string">&quot;A&quot;</span>, <span class="hljs-string">&quot;B&quot;</span>, <span class="hljs-string">&quot;C&quot;</span>, <span class="hljs-string">&quot;D&quot;</span>]<br>y_data = [<span class="hljs-number">10</span>, <span class="hljs-number">20</span>, <span class="hljs-number">30</span>, <span class="hljs-number">40</span>]<br><br><span class="hljs-comment"># 创建柱状图对象</span><br>bar = Bar(init_opts=opts.InitOpts(width=<span class="hljs-string">&quot;500px&quot;</span>, height=<span class="hljs-string">&quot;300px&quot;</span>))<br><br><span class="hljs-comment"># 添加x轴数据</span><br>bar.add_xaxis(x_data)<br><br><span class="hljs-comment"># 添加y轴数据</span><br>bar.add_yaxis(<span class="hljs-string">&quot;柱状图&quot;</span>, y_data)<br><br><span class="hljs-comment"># 设置全局选项</span><br>bar.set_global_opts(title_opts=opts.TitleOpts(title=<span class="hljs-string">&quot;柱状图示例&quot;</span>))<br><br><span class="hljs-comment"># 绘图并保存</span><br>bar.render(<span class="hljs-string">&quot;bar_chart.html&quot;</span>)<br></code></pre></td></tr></table></figure>

<p><img src="https://gitee.com/deng-2022/pictures/raw/master/images/image-20231016194851306.png" alt="image-20231016194851306"></p>
<h2 id="Python-期末小组作业（旧）"><a href="#Python-期末小组作业（旧）" class="headerlink" title="Python 期末小组作业（旧）"></a>Python 期末小组作业（旧）</h2><ul>
<li>人工智能、Python课程的期末小组作业目前有想法，这俩门课程研究一个课题吧</li>
</ul>
<h2 id="课题名称"><a href="#课题名称" class="headerlink" title="课题名称"></a>课题名称</h2><ul>
<li><h5 id="智能生成图表"><a href="#智能生成图表" class="headerlink" title="智能生成图表"></a>智能生成图表</h5></li>
</ul>
<h2 id="效果展示"><a href="#效果展示" class="headerlink" title="效果展示"></a>效果展示</h2><ul>
<li>PPT，展示生成的图表</li>
</ul>
<h2 id="开发工具"><a href="#开发工具" class="headerlink" title="开发工具"></a>开发工具</h2><ul>
<li>PyCharm</li>
</ul>
<h2 id="课题分析"><a href="#课题分析" class="headerlink" title="课题分析"></a>课题分析</h2><ul>
<li><p>生成图表三步骤：<strong>（2023/10/12早）</strong></p>
<ul>
<li>数据（构造数据，自行搜集资料构造数据）<ul>
<li><strong>数据样式选择</strong>（方便接下来导入数据，作数据分析）<ul>
<li>JSON 字符串，使用 Python 基础语法解构 JSON 字符串，获取数据</li>
<li>Excel 图表，使用 Python 自带工具类，导入 Excel 图表，解构图表获取数据</li>
</ul>
</li>
</ul>
</li>
<li>导入数据：使用上述两种方式将数据导入完成后，智能分析，生成图表</li>
<li>智能分析</li>
</ul>
</li>
<li><p>代码讲解：</p>
<ul>
<li>整体架构：上述三步骤</li>
<li>构造数据简单讲解（JSON 字符串样式）</li>
<li>列表、元组语法简单讲解</li>
<li>亮点（重点）：如何解构 JSON 字符串/ Excel 图表获得数据</li>
<li>生成图表简单讲解</li>
</ul>
</li>
<li><p>闲话</p>
</li>
</ul>
<h2 id="Python-期末小组作业（新）"><a href="#Python-期末小组作业（新）" class="headerlink" title="Python 期末小组作业（新）"></a>Python 期末小组作业（新）</h2><h3 id="实现思路"><a href="#实现思路" class="headerlink" title="实现思路"></a>实现思路</h3><p>构思一下整个 <strong>Python 课设</strong>的实现思路：</p>
<ul>
<li><p><code>实验目的</code>：</p>
<ul>
<li><p>掌握 <strong>Python 基础语法</strong>：函数定义与调用、条件分支、对象创建</p>
</li>
<li><p>掌握在 Python 中使用第三方库对 <strong>Excel 表格分析</strong>思路与具体实现</p>
</li>
<li><p>掌握<strong>使用 Python 实现数据库连接</strong>，并实现对数据<strong>基本的增、删、改、查</strong>操作 <strong>（2023/11/09晚）</strong></p>
</li>
</ul>
</li>
<li><p><code>功能实现</code>：</p>
<ul>
<li><strong>数据存储</strong>：使用 <code>Python</code> 分析 <code>Excel</code> 表格中的数据，存储到数据库中</li>
</ul>
<blockquote>
<ul>
<li>连接本地数据库（如SQLite、MySQL等）。<strong>（2023/11/25早）</strong></li>
<li>创建数据表，根据Excel表格的列名和数据类型定义表结构。</li>
<li>读取Excel表格中的数据，可以使用pandas库进行操作。</li>
<li>将读取到的数据插入到数据库中，可以使用pandas的to_sql方法。</li>
</ul>
</blockquote>
<ul>
<li><strong>数据更新</strong>：更新数据库中的数据记录</li>
</ul>
<blockquote>
<ul>
<li>模拟请求，生成需要更新的数据记录。</li>
<li>使用Python连接到数据库，执行更新操作。</li>
<li>更新数据库中的数据记录，可以使用SQL语句或ORM框架（如SQLAlchemy）进行操作。</li>
</ul>
</blockquote>
<ul>
<li><strong>数据写回</strong>：从数据库中查询记录，生成统计图表展示数据，生成 Excel 表格，适当优化表格样式后，保存表格到本地</li>
</ul>
<blockquote>
<ul>
<li>从数据库中查询记录，可以使用SQL语句或ORM框架进行查询。</li>
<li>对查询结果进行处理，例如计算统计指标、生成图表等。</li>
<li>将处理后的数据写入Excel表格，可以使用pandas的DataFrame对象进行操作。</li>
<li>适当优化表格样式，可以使用pandas的样式函数进行设置。</li>
<li>保存Excel表格到本地文件系统。</li>
</ul>
</blockquote>
</li>
<li><p><code>开发文档</code></p>
<ul>
<li><p><strong>图文并举</strong>，描述上述功能的具体实现</p>
</li>
<li><p>实现数据存储：连接本地数据库，新增数据实体，分析 Excel 表格数据，写入数据库</p>
</li>
<li><p>实现数据更新：模拟请求，更新数据库数据，掌握使用 Python 实现本地数据库的更新</p>
</li>
<li><p>实现数据写回：掌握如何在 Python 中实现数据库记录的查询（查询全表）</p>
</li>
</ul>
</li>
<li><p><code>操作手册</code></p>
<ul>
<li>连个可视化页面都没有，何谈操作手册？</li>
<li>主要是给开发者练手用的，本来就不是一个完整的应用</li>
</ul>
</li>
<li><p><code>学习价值和应用场景</code></p>
<ul>
<li><p>做这个大作业的好处有很多，以下是一些可能的学习价值和应用场景：</p>
<ol>
<li>学习价值方面：<ul>
<li>提高编程能力：通过完成这个大作业，你可以锻炼自己的编程技巧和解决问题的能力。你将学习如何设计和实现一个完整的应用程序，并处理各种挑战和错误。</li>
<li>加深对Python的理解：这个大作业将帮助你更深入地理解Python语言的各个方面，包括语法、数据类型、函数、类等。你将有机会应用这些知识来解决实际问题。</li>
<li>掌握数据处理和分析技能：通过使用Excel表格和数据库进行数据处理和分析，你将学习如何处理大量的数据，并进行统计和可视化展示。这对于数据分析和决策支持方面的工作非常有用。</li>
<li>培养团队合作能力：如果你选择与同学一起完成这个大作业，你将学会与他人合作、分工协作，共同解决问题。这有助于培养你的团队合作能力和沟通能力。</li>
</ul>
</li>
<li>具体应用场景：<ul>
<li>数据存储和管理：这个大作业可以帮助你学习如何使用Python连接数据库，并将数据存储到数据库中。这对于需要管理大量数据的应用程序非常有用，例如电子商务网站、社交媒体平台等。</li>
<li>数据分析和报告生成：通过使用Excel表格和数据库进行数据分析，你可以生成各种报告和图表，用于业务分析和决策支持。这对于企业、研究机构和政府部门都非常有用。</li>
<li>数据更新和维护：这个大作业可以帮助你学习如何使用Python更新数据库中的数据记录。这对于需要频繁更新和维护数据的应用程序非常重要，例如客户关系管理系统、库存管理系统等。</li>
<li>自动化数据处理流程：通过编写Python脚本来自动执行数据处理任务，你可以节省时间和精力，并提高工作效率。这对于需要处理大量重复性任务的工作非常有帮助，例如数据清洗、数据转换等。</li>
</ul>
</li>
</ol>
<ul>
<li>总之，这个大作业不仅能够提升你的编程能力和数据处理技能，还能为你未来的学习和职业发展打下坚实的基础。无论是在学术研究、商业应用还是工程开发领域，掌握这些技能都将使你更具竞争力。</li>
</ul>
</li>
</ul>
</li>
</ul>
<h3 id="开发日志"><a href="#开发日志" class="headerlink" title="开发日志"></a>开发日志</h3><blockquote>
<p>2023/11/25</p>
</blockquote>
<ul>
<li>今天开始着手开发这个大作业了，，祝我一切顺利</li>
<li>简单回忆学习了下如何在不同包之间实现函数调用，感觉还是先实现功能吧，把框架搭好，按步骤一步一步慢慢实现<strong>（2023/11/25早）</strong></li>
</ul>
<blockquote>
<p>2023/11/26</p>
</blockquote>
<ul>
<li>今早完成了数据库连接、查询数据库记录并用实体类接收、分析生成图表：</li>
</ul>
<p><img src="https://gitee.com/deng-2022/pictures/raw/master/images/image-20231126115535582.png" alt="image-20231126115535582"></p>
<h2 id="数据处理"><a href="#数据处理" class="headerlink" title="数据处理"></a>数据处理</h2><h3 id="Python-处理-Excel-表格"><a href="#Python-处理-Excel-表格" class="headerlink" title="Python 处理 Excel 表格"></a>Python 处理 Excel 表格</h3><blockquote>
<h5 id="🔥-推荐阅读："><a href="#🔥-推荐阅读：" class="headerlink" title="🔥 推荐阅读："></a>🔥 推荐阅读：</h5><p><a target="_blank" rel="noopener" href="https://blog.csdn.net/lm_love_hxl/article/details/130733070">Python操作Excel教程（全网最全，只看这一篇就够）_python excel-CSDN博客</a></p>
<p><a target="_blank" rel="noopener" href="https://zhuanlan.zhihu.com/p/634950523">如何使用python处理excel表格 - 知乎 (zhihu.com)</a></p>
</blockquote>
<h4 id="代码展示"><a href="#代码展示" class="headerlink" title="代码展示"></a>代码展示</h4><ul>
<li>今天中午第一次尝试<strong>使用 Python 处理 Excel 表格</strong>，找到了一段简短的实例代码： <strong>（2023/11/06晚）</strong></li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-comment"># 导入 pandas</span><br><span class="hljs-keyword">import</span> pandas <span class="hljs-keyword">as</span> pd<br><br><span class="hljs-comment"># 读取Excel文件</span><br>df = pd.read_excel(<span class="hljs-string">&#x27;职工表.xlsx&#x27;</span>)<br><br><span class="hljs-comment"># 打印数据框的内容</span><br><span class="hljs-built_in">print</span>(df)<br></code></pre></td></tr></table></figure>

<ul>
<li><strong>直接运行</strong>，结果如下：</li>
</ul>
<p><img src="C:\Users\Lenovo\AppData\Roaming\Typora\typora-user-images\image-20231106134654086.png" alt="image-20231106134654086"></p>
<h4 id="报错处理"><a href="#报错处理" class="headerlink" title="报错处理"></a>报错处理</h4><ul>
<li>本来直接<strong>安装下载缺失的第三方库</strong>后，直接运行代码就可以了，但是一直不生效（<strong>这个报错没截到图片</strong>）<strong>（2023/11/06晚）</strong></li>
</ul>
<figure class="highlight cmake"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs cmake">pip <span class="hljs-keyword">install</span> pandas<br></code></pre></td></tr></table></figure>

<figure class="highlight cmake"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs cmake">pip <span class="hljs-keyword">install</span> openpyxl<br></code></pre></td></tr></table></figure>

<ul>
<li><p>它一直提示 “缺失第三方库 openpyxl”，但是我已经安装了</p>
</li>
<li><p>通过<strong>网络搜索</strong>、<strong>询问 AI</strong> 等方式，我先后尝试了多种方法，均无果：</p>
<ul>
<li>查看 <code>openpyxl</code> 是否在当前环境中安装：</li>
</ul>
<figure class="highlight dart"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs dart">pip <span class="hljs-keyword">show</span> openpyxl<br></code></pre></td></tr></table></figure>

<ul>
<li>展示已安装的 <strong>第三方库</strong>：</li>
</ul>
<figure class="highlight ebnf"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs ebnf"><span class="hljs-attribute">pip list</span><br></code></pre></td></tr></table></figure></li>
<li><h5 id="我清楚这是编译器卡了的缘故，重启-Pycharm-也没效果"><a href="#我清楚这是编译器卡了的缘故，重启-Pycharm-也没效果" class="headerlink" title="我清楚这是编译器卡了的缘故，重启 Pycharm 也没效果"></a>我清楚这是编译器卡了的缘故，重启 Pycharm 也没效果</h5></li>
<li><p>狗血的是，我在代码中显示引入了 openpyxl 库，结果就成功运行了（<strong>这段删了也没事，主要是右键编译器自动导入成功了</strong>）</p>
</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">import</span> openpyxl<br><span class="hljs-keyword">import</span> pandas <span class="hljs-keyword">as</span> pd<br><br><span class="hljs-comment"># 读取Excel文件</span><br>df = pd.read_excel(<span class="hljs-string">&#x27;职工表.xlsx&#x27;</span>)<br><br><span class="hljs-comment"># 打印数据框的内容</span><br><span class="hljs-built_in">print</span>(df)<br></code></pre></td></tr></table></figure>

<ul>
<li>看来我<strong>主动在终端安装下载</strong>第三方库不管用啊，还得<strong>显示导入</strong> <strong>（2023/11/06晚）</strong></li>
</ul>
<h4 id="openpyxl-处理数据-demo"><a href="#openpyxl-处理数据-demo" class="headerlink" title="openpyxl 处理数据 demo"></a>openpyxl 处理数据 demo</h4><ul>
<li>示例代码如下：</li>
</ul>
<blockquote>
<p>实现了对 Excel 表格的读取、数据新增、删除、、修改等功能</p>
</blockquote>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">def</span> <span class="hljs-title function_">openpyxl_demo</span>():<br>    <span class="hljs-comment"># 加载工作簿</span><br>    wb = load_workbook(filename=<span class="hljs-string">&#x27;职工表.xlsx&#x27;</span>)<br><br>    <span class="hljs-comment"># 获取工作表</span><br>    ws = wb.active<br><br>    <span class="hljs-comment"># 获取行和列的数量</span><br>    max_row = ws.max_row<br>    max_col = ws.max_column<br><br>    <span class="hljs-comment"># 遍历工作表中的每一个单元格，并打印其值</span><br>    <span class="hljs-keyword">for</span> row <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-number">1</span>, max_row):<br>        <span class="hljs-keyword">for</span> col <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-number">1</span>, max_col):<br>            cell = ws.cell(row=row, column=col)<br>            <span class="hljs-built_in">print</span>(cell.value, end=<span class="hljs-string">&#x27; &#x27;</span>)<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&#x27;\n&#x27;</span>)<br><br>    ws.append([<span class="hljs-number">8</span>, <span class="hljs-string">&quot;邓几把&quot;</span>, <span class="hljs-number">24</span>, <span class="hljs-string">&quot;流氓&quot;</span>])<br>    ws.append([<span class="hljs-number">8</span>, <span class="hljs-string">&quot;邓几把&quot;</span>, <span class="hljs-number">24</span>, <span class="hljs-string">&quot;流氓&quot;</span>])<br>    ws.append([<span class="hljs-number">8</span>, <span class="hljs-string">&quot;邓几把&quot;</span>, <span class="hljs-number">24</span>, <span class="hljs-string">&quot;流氓&quot;</span>])<br><br>    wb.save(<span class="hljs-string">&#x27;职工表.xlsx&#x27;</span>)<br></code></pre></td></tr></table></figure>

<ul>
<li>注：操作对应 Excel 表时，确保文件未打开，否则会出现 <code>无权限修改该文件</code> 的报错：<strong>（2023/11/07午）</strong></li>
</ul>
<p><img src="https://gitee.com/deng-2022/pictures/raw/master/images/image-20231107134830545.png" alt="image-20231107134830545"></p>
<h2 id="Python-连接数据库"><a href="#Python-连接数据库" class="headerlink" title="Python 连接数据库"></a>Python 连接数据库</h2><ul>
<li>作为 Python 大作业的一部分，今晚测试一下<strong>使用 Python 连接本地数据库</strong>的 demo 代码：</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">import</span> mysql.connector<br><br><span class="hljs-comment"># 创建数据库连接</span><br>cnx = mysql.connector.connect(<br>    host=<span class="hljs-string">&quot;localhost&quot;</span>,  <span class="hljs-comment"># 数据库主机地址</span><br>    port=<span class="hljs-string">&quot;3306&quot;</span>,  <span class="hljs-comment"># 数据库端口号</span><br>    user=<span class="hljs-string">&quot;****&quot;</span>,  <span class="hljs-comment"># 数据库用户名</span><br>    password=<span class="hljs-string">&quot;****&quot;</span>,  <span class="hljs-comment"># 数据库密码</span><br>    database=<span class="hljs-string">&quot;****&quot;</span>  <span class="hljs-comment"># 数据库名称</span><br>)<br><br>cursor = cnx.cursor()<br><br><span class="hljs-comment"># 执行查询语句</span><br>cursor.execute(<span class="hljs-string">&quot;SELECT * FROM article&quot;</span>)<br><br><span class="hljs-comment"># 获取查询结果</span><br>results = cursor.fetchall()<br><br><span class="hljs-comment"># 处理查询结果</span><br><span class="hljs-keyword">for</span> row <span class="hljs-keyword">in</span> results:<br>    <span class="hljs-built_in">print</span>(row)<br></code></pre></td></tr></table></figure>

<ul>
<li>执行结果如下，<strong>成功执行 SQL</strong>，查询到数据库中的数据：<strong>（2023/11/15晚）</strong></li>
</ul>
<p><img src="https://gitee.com/deng-2022/pictures/raw/master/images/image-20231115220719115.png" alt="image-20231115220719115"></p>
<h2 id="人脸识别"><a href="#人脸识别" class="headerlink" title="人脸识别"></a>人脸识别</h2><ul>
<li>这个挺有意思的，记录一下<strong>（2023/11/25午）</strong></li>
</ul>
<p><img src="https://gitee.com/deng-2022/pictures/raw/master/images/image-20231125144542784.png" alt="image-20231125144542784"></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-comment"># 导入必要的包</span><br><span class="hljs-keyword">import</span> cv2<br><br><span class="hljs-comment"># 读入要检测的图像</span><br><span class="hljs-comment"># face_image = cv2.imread(&quot;pic1.JPG&quot;)</span><br>face_image = cv2.imread(<span class="hljs-string">&quot;pic2.JPG&quot;</span>)<br><br><span class="hljs-comment"># 加载人脸检测器</span><br>face_model = cv2.CascadeClassifier(<span class="hljs-string">&#x27;haarcascade_frontalface_default.xml&#x27;</span>)<br><br><span class="hljs-comment"># 人脸检测</span><br>faces = face_model.detectMultiScale(face_image, <span class="hljs-number">1.3</span>)<br><span class="hljs-built_in">print</span>(faces)<br><br><span class="hljs-comment"># 绘制矩形框</span><br><span class="hljs-keyword">for</span> (x, y, w, h) <span class="hljs-keyword">in</span> faces:<br>    cv2.rectangle(face_image, (x, y), (x + w, y + h), (<span class="hljs-number">0</span>, <span class="hljs-number">255</span>, <span class="hljs-number">0</span>), <span class="hljs-number">2</span>)<br><br><span class="hljs-comment"># 显示图像</span><br>cv2.imshow(<span class="hljs-string">&quot;detection result&quot;</span>, face_image)<br>cv2.waitKey(<span class="hljs-number">0</span>)<br>cv2.destroyAllWindows()<br></code></pre></td></tr></table></figure>

<h2 id="开发个人工具包"><a href="#开发个人工具包" class="headerlink" title="开发个人工具包"></a>开发个人工具包</h2><ul>
<li>上午突然冒出来的想法，原本打算随便操作数据库，作数据查询、插入、修改等，再使用第三方库做做可视化分析，生成个图表啥的</li>
<li>但是突然觉着太 low 了，最主要的还是没啥实际用途，权当巩固复习 Python 基础语法了</li>
<li>那我干脆一不做二不休，开发一个：个人工具包，包含日常学习办公常用的功能，目前的想法：<strong>（2023/11/27午）</strong></li>
</ul>
<p><img src="https://gitee.com/deng-2022/pictures/raw/master/images/image-20231127131901683.png" alt="image-20231127131901683"></p>
<ul>
<li><p>功能还比较少，但是上述想法，目前基本都能实现，我快速了解了我需要学习的相关技术：</p>
<ul>
<li><p>Python 程序 打包为 .exe 可执行文件：</p>
<blockquote>
<p><a target="_blank" rel="noopener" href="https://juejin.cn/post/6943901290325868552">【5分钟搞定】如何将py打包成exe可执行文件 - 掘金 (juejin.cn)</a></p>
</blockquote>
</li>
<li><p>使用 Python 进行简单界面开发：</p>
<blockquote>
<p><a target="_blank" rel="noopener" href="https://juejin.cn/post/7191537962985717819">Python 内置界面开发框架 Tkinter入门篇 甲 - 掘金 (juejin.cn)</a></p>
</blockquote>
</li>
<li><p>有趣的小游戏：贪吃蛇、拥抱梅西、羊了个羊</p>
</li>
</ul>
</li>
<li><p>先写这些吧，想法很多，也算是完成了我一直以来的心愿了，另外，这让我回忆起了尝试使用 Java 开发 MC 模组：</p>
</li>
</ul>
<blockquote>
<p>基本了解到了如何开发一个 MC mod 了，有机会试试 <strong>（2023/11/13午）</strong></p>
<p><a target="_blank" rel="noopener" href="https://space.bilibili.com/275212628/article">Alex3236博客-Alex3236专栏文章-文集-哔哩哔哩视频 (bilibili.com)</a></p>
</blockquote>
<h3 id="Python-程序打包为-exe"><a href="#Python-程序打包为-exe" class="headerlink" title="Python 程序打包为 .exe"></a>Python 程序打包为 .exe</h3><blockquote>
<p>🔥 推荐阅读：<a target="_blank" rel="noopener" href="https://juejin.cn/post/6943901290325868552">【5分钟搞定】如何将py打包成exe可执行文件 - 掘金 (juejin.cn)</a></p>
</blockquote>
<ul>
<li>安装 <code>pyinstaller</code>：<strong>（2023/11/27早）</strong></li>
</ul>
<figure class="highlight cmake"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs cmake">pip <span class="hljs-keyword">install</span> pyinstaller<br></code></pre></td></tr></table></figure>

<ul>
<li>执行打包：</li>
</ul>
<figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs nginx"><span class="hljs-attribute">pyinstaller</span> **<span class="hljs-regexp">*.py</span><br></code></pre></td></tr></table></figure>

<ul>
<li>妈的，安装了半小时 <code>pyinstaller</code>，修改了 <code>python</code> 路径，咯噔了半天，又可以了：</li>
</ul>
<p><img src="https://gitee.com/deng-2022/pictures/raw/master/images/image-20231127125712770.png" alt="image-20231127125712770"></p>
<ul>
<li>打包成功！我们尝试执行一下：</li>
</ul>
<p><img src="https://gitee.com/deng-2022/pictures/raw/master/images/image-20231127130742344.png" alt="image-20231127130742344"></p>
<ul>
<li>在 dist 目录下找到可执行文件 <code>.exe</code>，<strong>双击执行</strong>：</li>
</ul>
<p><img src="https://gitee.com/deng-2022/pictures/raw/master/images/image-20231127130849980.png" alt="image-20231127130849980"></p>
<p><img src="https://gitee.com/deng-2022/pictures/raw/master/images/image-20231127130933730.png" alt="image-20231127130933730"></p>
<ul>
<li>注意，我们只需要<strong>将 dist 目录下的文件压缩打包</strong>后，就可以发给好朋友使用了</li>
</ul>
<h3 id="Python-实现界面开发"><a href="#Python-实现界面开发" class="headerlink" title="Python 实现界面开发"></a>Python 实现界面开发</h3><blockquote>
<p><a target="_blank" rel="noopener" href="https://juejin.cn/post/7280837735614005287?searchId=202311272018327C19350FE1F6A9F74B8B">Python 程序员过中秋Python+pygame 制作拼图中秋赏月小游戏（附源码：5源码） - 掘金 (juejin.cn)</a></p>
</blockquote>
<ul>
<li>详细的练习代码已经上传至 Gitee 了，最后照着示例，实现了一个简单的笔记本案例：</li>
<li>如下：</li>
</ul>
<p><img src="C:\Users\Lenovo\AppData\Roaming\Typora\typora-user-images\image-20231127202157653.png" alt="image-20231127202157653"></p>
<ul>
<li>成功打包该笔记本软件，马上扔给好兄弟玩玩<strong>（2023/11/27晚）</strong></li>
</ul>
<figure class="highlight gherkin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><code class="hljs gherkin">欢迎使用 notepad 笔记本软件<br>作者: <span class="hljs-meta">@Memory</span><br>  <br> <span class="hljs-symbol">*</span>  <br> (  `  <br> )\))(    (    )       (   (  <br>((_)()\  ))\  (     (  )(  )\ )  <br>(_()((_)/((_) )\  &#x27; )\(()\(()/(  <br>|<span class="hljs-string">  \/  (_)) _((_)) ((_)((_))(_))  </span><br><span class="hljs-string"></span>|<span class="hljs-string"> </span>|<span class="hljs-string">\/</span>|<span class="hljs-string"> / -_) &#x27;  \() _ \ &#x27;_</span>|<span class="hljs-string"> </span>||<span class="hljs-string"> </span>|<span class="hljs-string">  </span><br><span class="hljs-string"></span>|<span class="hljs-string">_</span>|<span class="hljs-string">  </span>|<span class="hljs-string">_\___</span>|<span class="hljs-string">_</span>|<span class="hljs-string">_</span>|<span class="hljs-string">_</span>|<span class="hljs-string">\___/_</span>|<span class="hljs-string">  \_, </span>|<span class="hljs-string">  </span><br><span class="hljs-string">                           </span>|<span class="hljs-string">__/  </span><br><span class="hljs-string"></span><br><span class="hljs-string">您可以用它来编辑文本文件，也可以快捷地统计文本字数</span><br><span class="hljs-string">新的功能还在逐步开发完善中，敬请期待~</span><br><span class="hljs-string">您不需要理会这个窗口，祝您使用愉快</span><br><span class="hljs-string"></span><br></code></pre></td></tr></table></figure>

<p><img src="C:\Users\Lenovo\AppData\Roaming\Typora\typora-user-images\image-20231127211054419.png" alt="image-20231127211054419"></p>
<h3 id="新建窗口"><a href="#新建窗口" class="headerlink" title="新建窗口"></a>新建窗口</h3><ul>
<li>点击按钮，新建窗口<strong>（2023/11/28午）</strong></li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-comment"># 定义一个函数，用于创建新的窗口</span><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">create_new_window</span>(<span class="hljs-params">root</span>):<br>    new_window = tk.Toplevel(root)  <span class="hljs-comment"># 创建新的窗口实例</span><br>    new_window.title(<span class="hljs-string">&quot;新窗口&quot;</span>)  <span class="hljs-comment"># 设置新窗口的标题</span><br>    new_window.geometry(<span class="hljs-string">&quot;400x300+500+250&quot;</span>)<br>    label = tk.Label(new_window, text=<span class="hljs-string">&quot;这是新窗口&quot;</span>, font=(<span class="hljs-string">&quot;Arial&quot;</span>, <span class="hljs-number">18</span>))  <span class="hljs-comment"># 在新窗口中添加标签</span><br>    label.pack(pady=<span class="hljs-number">50</span>)  <span class="hljs-comment"># 添加标签并设置垂直空间</span><br><br>    <span class="hljs-comment"># 在新窗口中添加标签</span><br>    label = tk.Label(new_window, text=<span class="hljs-string">&quot;这是新窗口&quot;</span>, font=(<span class="hljs-string">&quot;Arial&quot;</span>, <span class="hljs-number">18</span>))<br>    label.pack(pady=<span class="hljs-number">50</span>)<br></code></pre></td></tr></table></figure>

<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-comment"># 在下层Frame中添加按钮</span><br>button = tk.Button(bottom_frame, text=<span class="hljs-string">&quot;开始使用&quot;</span>, font=(<span class="hljs-string">&quot;Arial&quot;</span>, <span class="hljs-number">10</span>), command=<span class="hljs-keyword">lambda</span>: create_new_window(root))<br>button.pack()<br></code></pre></td></tr></table></figure>

<ul>
<li>为 <code>Button</code> 按钮绑定了一个点击事件 <code>create_new_window</code>，创建了一个新窗口</li>
</ul>
<h3 id="一个用法震撼我两遍"><a href="#一个用法震撼我两遍" class="headerlink" title="一个用法震撼我两遍"></a>一个用法震撼我两遍</h3><ul>
<li>注意到上面 <code>Button</code> 按钮绑定事件的方法没：</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs python">button = tk.Button(bottom_frame, text=<span class="hljs-string">&quot;开始使用&quot;</span>, font=(<span class="hljs-string">&quot;Arial&quot;</span>, <span class="hljs-number">10</span>), command=<span class="hljs-keyword">lambda</span>: create_new_window(root))<br></code></pre></td></tr></table></figure>

<ul>
<li>我们实现窗口上实时显示时间：</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">def</span> <span class="hljs-title function_">update_time</span>(<span class="hljs-params">label, window</span>):<br>    <span class="hljs-comment"># 获取当前时间并格式化为字符串</span><br>    current_time = datetime.datetime.now().strftime(<span class="hljs-string">&#x27;%Y-%m-%d %H:%M:%S&#x27;</span>)<br>    <span class="hljs-comment"># 更新Label的文本为当前时间</span><br>    label[<span class="hljs-string">&#x27;text&#x27;</span>] = current_time<br>    window.after(<span class="hljs-number">1000</span>, <span class="hljs-keyword">lambda</span>: update_time(label, window))  <span class="hljs-comment"># 开始时调用一次update_time函数，之后每秒更新一次时间</span><br></code></pre></td></tr></table></figure>

<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs python">new_window = tk.Toplevel(root)  <span class="hljs-comment"># 创建新的窗口实例</span><br>    new_window.title(<span class="hljs-string">&quot;新窗口&quot;</span>)  <span class="hljs-comment"># 设置新窗口的标题</span><br>    new_window.geometry(<span class="hljs-string">&quot;400x300+500+250&quot;</span>)<br>    label = tk.Label(new_window, text=<span class="hljs-string">&quot;这是新窗口&quot;</span>, font=(<span class="hljs-string">&quot;Arial&quot;</span>, <span class="hljs-number">18</span>))  <span class="hljs-comment"># 在新窗口中添加标签</span><br>    label.pack(pady=<span class="hljs-number">50</span>)  <span class="hljs-comment"># 添加标签并设置垂直空间</span><br><br>    <span class="hljs-comment"># 在新窗口中添加标签</span><br>    label = tk.Label(new_window, text=<span class="hljs-string">&quot;这是新窗口&quot;</span>, font=(<span class="hljs-string">&quot;Arial&quot;</span>, <span class="hljs-number">18</span>))<br>    label.pack(pady=<span class="hljs-number">50</span>)<br><br>    <span class="hljs-comment"># 创建定时器，每隔1秒更新时间</span><br>    new_window.after(<span class="hljs-number">1000</span>, <span class="hljs-keyword">lambda</span>: update_time(label, new_window))  <span class="hljs-comment"># 开始时调用一次update_time函数，之后每秒更新一次时间</span><br></code></pre></td></tr></table></figure>

<ul>
<li>效果如下：</li>
</ul>
<p><img src="https://gitee.com/deng-2022/pictures/raw/master/images/image-20231128120751320.png" alt="image-20231128120751320"></p>
<ul>
<li>对于该函数用法的解释（文心一言）：<strong>（2023/11/28午）</strong></li>
</ul>
<blockquote>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs python">root.after(<span class="hljs-number">1000</span>, update_time(label, root))<br></code></pre></td></tr></table></figure>

<p>你在这里直接调用了<code>update_time(label, root)</code>，这样的话，<code>update_time</code>函数会在主线程中立即执行，而不是在定时器触发后执行。因此，<code>update_time</code>函数只会被调用一次，而不是每秒一次。</p>
<p>正确的方法是将函数本身传递给<code>after</code>方法，而不是函数的执行结果。你可以使用一个lambda函数来解决这个问题，如下所示：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs python">root.after(<span class="hljs-number">1000</span>, <span class="hljs-keyword">lambda</span>: update_time(label, root))<br></code></pre></td></tr></table></figure>

<p>lambda: update_time(label, root)<code> 是一个匿名函数，它会在指定的时间后执行</code>update_time(label, root)<code>，这样就可以保证</code>update_time`函数每秒被调用一次了。</p>
</blockquote>
<h3 id="点击执行一个可执行文件"><a href="#点击执行一个可执行文件" class="headerlink" title="点击执行一个可执行文件"></a>点击执行一个可执行文件</h3><ul>
<li>为什么会有这样的想法呢？我打算开发一个小游戏模块，这个模块有哪些小游戏呢？展示一下目前的想法吧：</li>
</ul>
<blockquote>
<p>拼图游戏、黄金矿工、贪吃蛇、扫雷、羊了个羊</p>
</blockquote>
<ul>
<li>黄金矿工的话，之前用 Java 实现过，整体做工比较精良，我可不想再用 Python 写一遍</li>
<li>目前的想法就是在该工具包下内嵌一个黄金矿工小游戏，直接点击按钮就能执行<strong>（2023/11/28午）</strong></li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">def</span> <span class="hljs-title function_">execute_executable</span>():<br>    <span class="hljs-comment"># 指定可执行文件的完整路径</span><br>    executable_path = <span class="hljs-string">&quot;E:\Singal_Games\GoldMiner\GoldMiner.exe&quot;</span><br>    <span class="hljs-comment"># executable_path = &quot;D:\Project\python\程序打包\界面编程\GoldMiner\GoldMiner.exe&quot;</span><br><br>    <span class="hljs-comment"># 执行可执行文件</span><br>    process = subprocess.Popen(executable_path)<br><br><br><span class="hljs-comment"># 创建主窗口</span><br>root = tk.Tk()<br>root.title(<span class="hljs-string">&quot;执行可执行文件&quot;</span>)<br><br><span class="hljs-comment"># 创建按钮并绑定事件</span><br>button = tk.Button(root, text=<span class="hljs-string">&quot;执行可执行文件&quot;</span>, command=execute_executable)<br>button.pack(pady=<span class="hljs-number">20</span>)<br><br><span class="hljs-comment"># 启动主窗口的事件循环</span><br>root.mainloop()<br></code></pre></td></tr></table></figure>

<h3 id="英汉互译"><a href="#英汉互译" class="headerlink" title="英汉互译"></a>英汉互译</h3><ul>
<li>简单的英汉互译测试：</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">from</span> translate <span class="hljs-keyword">import</span> Translator<br><br>text = <span class="hljs-string">&#x27;&#x27;&#x27;</span><br><span class="hljs-string">在Python编程领域，我们常常需要处理多语言文本，而翻译工具就成为了必不可少的利器。今天，我们将介绍一个强大的Python翻译库——translate。</span><br><span class="hljs-string">&#x27;&#x27;&#x27;</span><br><br>text2 = <span class="hljs-string">&#x27;&#x27;&#x27;</span><br><span class="hljs-string">go and fuck yourself</span><br><span class="hljs-string">&#x27;&#x27;&#x27;</span><br><br>translator = Translator(from_lang=<span class="hljs-string">&quot;zh&quot;</span>, to_lang=<span class="hljs-string">&quot;en&quot;</span>)<br>translator2 = Translator(from_lang=<span class="hljs-string">&quot;en&quot;</span>, to_lang=<span class="hljs-string">&quot;zh&quot;</span>)<br><br>translated_text = translator.translate(text)<br>translated_text2 = translator2.translate(text2)<br><br><span class="hljs-built_in">print</span>(translated_text)<br><span class="hljs-built_in">print</span>(translated_text2)<br></code></pre></td></tr></table></figure>

<p><img src="https://gitee.com/deng-2022/pictures/raw/master/images/image-20231128144220210.png" alt="image-20231128144220210"></p>
<ul>
<li>成功实现<strong>英汉互译小程序</strong>，成功打包，发给好兄弟试试：<strong>（2023/11/28午）</strong></li>
</ul>
<p><img src="https://gitee.com/deng-2022/pictures/raw/master/images/image-20231128144602464.png" alt="image-20231128144602464"></p>
<h3 id="开发者文档"><a href="#开发者文档" class="headerlink" title="开发者文档"></a>开发者文档</h3><ul>
<li><p>这么新颖的项目，怎么能没有开发者文档呢？只是让用户使用一个个干煸的窗口怎么行？</p>
</li>
<li><p>正好最近在研究 Memory API接口开放平台的开发者文档的编写 + 部署，历时三天可算搞完了</p>
</li>
<li><p>Memory API接口开放平台、Vuepress 文档站点、Python 小程序，三个方向看起来八竿子打不到一块，今天让我融会贯通了：</p>
<ul>
<li><p>Python 小程序提供的功能，也是Memory API接口开放平台所需要的，这极大地拓展了我对开放接口的想法</p>
</li>
<li><p>Memory API 接口开放平台需要一个开发者文档，用以详细介绍如何调用接口，包含接口信息、返回值、错误码等。那 Python小程序也很需要这些</p>
</li>
<li><p>VuePress 搭建文档站点并成功部署，这是很久以前的想法了，历时五个月，今天终于实现了</p>
<blockquote>
<p><a target="_blank" rel="noopener" href="https://deng-2022.gitee.io/vuepress-docs3/">Mem-API 开发者文档 (gitee.io)</a></p>
</blockquote>
</li>
<li><p>他奶奶的我可太兴奋了，待会儿就把这个过程记录下来<strong>（2023/11/28午）</strong></p>
</li>
</ul>
</li>
<li><p>那我们实现一个简单的网页跳转：</p>
</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">def</span> <span class="hljs-title function_">open_docs</span>():<br>    webbrowser.<span class="hljs-built_in">open</span>(<span class="hljs-string">&#x27;https://deng-2022.gitee.io/vuepress-docs3/&#x27;</span>)<br><br><span class="hljs-comment"># 创建一个新窗口</span><br>window = tk.Tk()<br>window.title(<span class="hljs-string">&quot;开发者文档跳转按钮&quot;</span>)<br><br><span class="hljs-comment"># 创建一个标签</span><br>label = tk.Label(window, text=<span class="hljs-string">&quot;点击下面的按钮跳转到开发者文档!&quot;</span>)<br>label.pack()<br><br><span class="hljs-comment"># 创建一个跳转按钮</span><br>button = tk.Button(window, text=<span class="hljs-string">&quot;跳转到开发者文档&quot;</span>, command=open_docs)<br>button.pack()<br><br><span class="hljs-comment"># 运行主循环</span><br>window.mainloop()<br></code></pre></td></tr></table></figure>

<ul>
<li>妈的，创建圆形按钮失败，<code>tkinter</code> 不支持</li>
</ul>
<h3 id="讯飞星火-API接口开放平台"><a href="#讯飞星火-API接口开放平台" class="headerlink" title="讯飞星火 API接口开放平台"></a>讯飞星火 API接口开放平台</h3><blockquote>
<p>推荐阅读：<a target="_blank" rel="noopener" href="https://www.iotword.com/15849.html">使用讯飞星火API，轻松打造个性化AI聊天机器人程序-物联沃-IOTWORD物联网</a></p>
</blockquote>
<ul>
<li>看下这篇文章就够了，也打包成功了，运行效果如下：<strong>（2023/11/28晚）</strong></li>
</ul>
<p><img src="C:\Users\Lenovo\AppData\Roaming\Typora\typora-user-images\image-20231128235619438.png" alt="image-20231128235619438"></p>
<ul>
<li>这样写的话，打包后运行 .exe 文件，窗口闪退了，尝试了一晚上还是没解决：</li>
</ul>
<blockquote>
<p><a target="_blank" rel="noopener" href="https://console.xfyun.cn/services/bm2">控制台-讯飞开放平台 (xfyun.cn)</a></p>
</blockquote>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-comment"># -*- coding:utf-8 -*-</span><br><span class="hljs-keyword">import</span> os<br><br>os.environ[<span class="hljs-string">&#x27;SPARK_APP_ID&#x27;</span>] = <span class="hljs-string">&quot;*****&quot;</span>  <span class="hljs-comment"># 星火大模型的APPID</span><br>os.environ[<span class="hljs-string">&#x27;SPARK_API_SECRET&#x27;</span>] = <span class="hljs-string">&quot;******&quot;</span>  <span class="hljs-comment"># 星火大模型的APISecret</span><br>os.environ[<span class="hljs-string">&#x27;SPARK_API_KEY&#x27;</span>] = <span class="hljs-string">&quot;******&quot;</span>  <span class="hljs-comment"># 星火大模型的APIKey</span><br>os.environ[<span class="hljs-string">&#x27;SPARK_API_MODEL&#x27;</span>] = <span class="hljs-string">&quot;v2.0&quot;</span><br>os.environ[<span class="hljs-string">&#x27;SPARK_CHAT_MAX_TOKENS&#x27;</span>] = <span class="hljs-string">&quot;4096&quot;</span><br>os.environ[<span class="hljs-string">&#x27;SPARK_CHAT_TEMPERATURE&#x27;</span>] = <span class="hljs-string">&quot;0.5&quot;</span><br>os.environ[<span class="hljs-string">&#x27;SPARK_CHAT_TOP_K&#x27;</span>] = <span class="hljs-string">&quot;4&quot;</span><br><br><span class="hljs-keyword">from</span> sparkapi.core.api <span class="hljs-keyword">import</span> SparkAPI<br><span class="hljs-keyword">from</span> sparkapi.core.config <span class="hljs-keyword">import</span> SparkConfig<br><br><span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">&#x27;__main__&#x27;</span>:<br>    Input = <span class="hljs-built_in">input</span>(<span class="hljs-string">&quot;开始对话吧！(单击Enter键开始)&quot;</span>)<br>    config = SparkConfig().model_dump()<br>    api = SparkAPI(**config)<br><br>    api.chat()<br><br>    res = api.get_completion(<span class="hljs-string">&#x27;hello&#x27;</span>)<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&#x27;&#x27;</span>.join(res))<br><br>    messages = [<br>        &#123;<span class="hljs-string">&#x27;role&#x27;</span>: <span class="hljs-string">&#x27;user&#x27;</span>, <span class="hljs-string">&#x27;content&#x27;</span>: <span class="hljs-string">&#x27;hello&#x27;</span>&#125;,<br>        &#123;<span class="hljs-string">&#x27;role&#x27;</span>: <span class="hljs-string">&#x27;assistant&#x27;</span>, <span class="hljs-string">&#x27;content&#x27;</span>: <span class="hljs-string">&#x27;Hello! How can I assist&#x27;</span>&#125;,<br>        &#123;<span class="hljs-string">&#x27;role&#x27;</span>: <span class="hljs-string">&#x27;user&#x27;</span>, <span class="hljs-string">&#x27;content&#x27;</span>: <span class="hljs-string">&#x27;write me a Python script of BubbleSort&#x27;</span>&#125;,<br>    ]<br>    res = api.get_completion_from_messages(messages)<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&#x27;&#x27;</span>.join(res))<br></code></pre></td></tr></table></figure>

<h3 id="图片爬取"><a href="#图片爬取" class="headerlink" title="图片爬取"></a>图片爬取</h3><ul>
<li>实现了一个简单的图片爬取软件，一键获取100+张图片！</li>
</ul>
<figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs"><br></code></pre></td></tr></table></figure>

<ul>
<li>妈的，好像被限制了还是咋的，本来打包就一直失败，现在本地都不能爬取了</li>
</ul>
<h3 id="天气预报"><a href="#天气预报" class="headerlink" title="天气预报"></a>天气预报</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><code class="hljs python">root = tk.Tk()  <span class="hljs-comment"># 创建主窗口</span><br>root.title(<span class="hljs-string">&quot;Weather Information&quot;</span>)  <span class="hljs-comment"># 设置窗口标题</span><br>root.geometry(<span class="hljs-string">&quot;600x300&quot;</span>)  <span class="hljs-comment"># 设置窗口大小（宽x高）</span><br>root.resizable(<span class="hljs-literal">False</span>, <span class="hljs-literal">False</span>)  <span class="hljs-comment"># 禁止调整窗口大小</span><br><br>text_area = scrolledtext.ScrolledText(root, height=<span class="hljs-number">10</span>)  <span class="hljs-comment"># 创建滚动文本框，用于显示天气信息</span><br>text_area.pack(fill=tk.BOTH, expand=<span class="hljs-literal">True</span>)  <span class="hljs-comment"># 添加滚动文本框到主窗口，并自动调整大小以适应窗口大小变化</span><br><br><span class="hljs-comment"># 创建关键词标签和输入框</span><br>keyword_label = tk.Label(root, text=<span class="hljs-string">&quot;城市名:&quot;</span>)<br>keyword_label.pack(pady=<span class="hljs-number">10</span>)<br>keyword_entry = tk.Entry(root)<br>keyword_entry.pack(pady=<span class="hljs-number">10</span>)<br><br><span class="hljs-comment"># 创建按钮并设置事件处理程序</span><br>button1 = tk.Button(root, text=<span class="hljs-string">&quot;天气查询&quot;</span>, font=(<span class="hljs-string">&quot;Arial&quot;</span>, <span class="hljs-number">12</span>),<br>                    command=<span class="hljs-keyword">lambda</span>: show_weather_info(keyword_entry.get()))<br>button1.pack(side=tk.TOP, padx=<span class="hljs-number">10</span>)<br><br>root.mainloop()  <span class="hljs-comment"># 启动主窗口的消息循环，显示窗口并等待用户操作</span><br></code></pre></td></tr></table></figure>

<ul>
<li>这里的 <code>keyword_entry.get()</code> 拿一个变量 <code>city</code> 接收的话，会报 Null 的错误，所以不用参数接收，直接传参了 </li>
<li>效果如下：<strong>（2023/12/01午）</strong></li>
</ul>
<p><img src="C:\Users\Lenovo\AppData\Roaming\Typora\typora-user-images\image-20231201142459038.png" alt="image-20231201142459038"></p>
<p><img src="C:\Users\Lenovo\AppData\Roaming\Typora\typora-user-images\image-20231201145026652.png" alt="image-20231201145026652"></p>
<h3 id="封装方法为一个类"><a href="#封装方法为一个类" class="headerlink" title="封装方法为一个类"></a>封装方法为一个类</h3><ul>
<li> 没错，<strong>面向对象编程的核心</strong>就是<strong>将具体功能封装到类中</strong>，这样能更好地组织和管理代码，同时也方便其他开发人员使用和共享这些功能。</li>
<li>这里以简易笔记本的实现为例，源代码：</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-comment"># 一个简单的笔记本</span><br><span class="hljs-keyword">import</span> tkinter <span class="hljs-keyword">as</span> tk<br><span class="hljs-keyword">import</span> tkinter.filedialog <span class="hljs-keyword">as</span> filedialog<br><br><br><span class="hljs-comment"># 打开文件</span><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">open_file</span>():<br>    file_path = filedialog.askopenfilename(<br>        filetypes=[<br>            (<span class="hljs-string">&quot;Text files&quot;</span>, <span class="hljs-string">&quot;*.txt&quot;</span>),<br>            (<span class="hljs-string">&quot;All files&quot;</span>, <span class="hljs-string">&quot;*.*&quot;</span>)<br>        ]<br>    )<br><br>    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> file_path:<br>        window.title(<span class="hljs-string">&quot;无标题 - 记事本&quot;</span>)<br>        <span class="hljs-keyword">return</span><br><br>    txt_edit.delete(<span class="hljs-string">&quot;1.0&quot;</span>, tk.END)<br><br>    <span class="hljs-keyword">with</span> <span class="hljs-built_in">open</span>(<br>            file_path,<br>            mode=<span class="hljs-string">&quot;r&quot;</span>,<br>            encoding=<span class="hljs-string">&quot;utf-8&quot;</span>) <span class="hljs-keyword">as</span> input_file:<br>        txt_edit.insert(<br>            tk.END,<br>            input_file.read()<br>        )<br>    window.title(<span class="hljs-string">f&quot;<span class="hljs-subst">&#123;file_path&#125;</span> - 记事本&quot;</span>)<br><br><br><span class="hljs-comment"># 另存为</span><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">save_as_file</span>():<br>    file_path = filedialog.asksaveasfilename(<br>        defaultextension=<span class="hljs-string">&quot;.txt&quot;</span>,<br>        filetypes=[<br>            (<span class="hljs-string">&quot;Text files&quot;</span>, <span class="hljs-string">&quot;*.txt&quot;</span>),<br>            (<span class="hljs-string">&quot;All files&quot;</span>, <span class="hljs-string">&quot;*.*&quot;</span>)<br>        ]<br>    )<br>    <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> file_path:<br>        <span class="hljs-keyword">return</span><br>    <span class="hljs-keyword">with</span> <span class="hljs-built_in">open</span>(<br>            file_path,<br>            mode=<span class="hljs-string">&quot;w&quot;</span>,<br>            encoding=<span class="hljs-string">&quot;utf-8&quot;</span>) <span class="hljs-keyword">as</span> output_file:<br>        output_file.write(txt_edit.get(<span class="hljs-string">&quot;1.0&quot;</span>, tk.END))<br>    window.title(<span class="hljs-string">f&quot;<span class="hljs-subst">&#123;file_path&#125;</span> - 记事本&quot;</span>)<br><br><br><span class="hljs-comment"># 统计字数</span><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">count_chars_in_text</span>():<br>    text = txt_edit.get(<span class="hljs-string">&quot;1.0&quot;</span>, tk.END)  <span class="hljs-comment"># 获取 Text 组件中的所有文本</span><br>    char_count = <span class="hljs-built_in">len</span>(text) - <span class="hljs-number">1</span>  <span class="hljs-comment"># 计算文本的长度</span><br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;字符数: <span class="hljs-subst">&#123;char_count&#125;</span>&quot;</span>)<br>    var_lbl.<span class="hljs-built_in">set</span>(<span class="hljs-string">f&quot;字符数: <span class="hljs-subst">&#123;char_count&#125;</span>&quot;</span>)  <span class="hljs-comment"># 显示文本</span><br><br><br>window = tk.Tk()<br>window.title(<span class="hljs-string">&quot;记事本&quot;</span>)<br><br>window.rowconfigure(<br>    <span class="hljs-number">0</span>,<br>    minsize=<span class="hljs-number">100</span>,<br>    weight=<span class="hljs-number">1</span><br>)<br>window.columnconfigure(<br>    <span class="hljs-number">1</span>,<br>    minsize=<span class="hljs-number">100</span>,<br>    weight=<span class="hljs-number">1</span><br>)<br><br><span class="hljs-comment"># 左侧操作区</span><br>btn_frame = tk.Frame(<br>    master=window,<br>    bd=<span class="hljs-number">2</span><br>)<br>btn_frame.grid(<br>    row=<span class="hljs-number">0</span>,<br>    column=<span class="hljs-number">0</span>,<br>    sticky=<span class="hljs-string">&quot;ns&quot;</span><br>)<br><br><span class="hljs-comment"># 打开文本文件</span><br>btn_open = tk.Button(<br>    master=btn_frame,<br>    text=<span class="hljs-string">&quot;打开&quot;</span>,<br>    command=open_file<br>)<br>btn_open.grid(<br>    row=<span class="hljs-number">0</span>,<br>    column=<span class="hljs-number">0</span>,<br>    sticky=<span class="hljs-string">&quot;ew&quot;</span>,<br>    padx=<span class="hljs-number">5</span>,<br>    pady=<span class="hljs-number">5</span><br>)<br><br><span class="hljs-comment"># 另存为</span><br>btn_save_as = tk.Button(<br>    master=btn_frame,<br>    text=<span class="hljs-string">&quot;另存&quot;</span>,<br>    command=save_as_file<br>)<br>btn_save_as.grid(<br>    row=<span class="hljs-number">1</span>,<br>    column=<span class="hljs-number">0</span>,<br>    sticky=<span class="hljs-string">&quot;ew&quot;</span>,<br>)<br><br><span class="hljs-comment"># 统计字数</span><br>btn_count = tk.Button(<br>    master=window,<br>    text=<span class="hljs-string">&quot;统计字数&quot;</span>,<br>    command=count_chars_in_text<br>)<br>btn_count.grid(row=<span class="hljs-number">1</span>, column=<span class="hljs-number">1</span>, sticky=<span class="hljs-string">&quot;ew&quot;</span>)<br><br><span class="hljs-comment"># 字符数</span><br>var_lbl = tk.StringVar()<br>var_lbl.<span class="hljs-built_in">set</span>(<span class="hljs-string">&quot;&quot;</span>)  <span class="hljs-comment"># 初始化一个空字符串</span><br><br>lbl = tk.Label(<br>    master=btn_count,<br>    textvariable=var_lbl<br>)<br><br>lbl.grid(row=<span class="hljs-number">1</span>, column=<span class="hljs-number">1</span>, sticky=<span class="hljs-string">&quot;ew&quot;</span>)<br><br><span class="hljs-comment"># 读写区</span><br>txt_edit = tk.Text(master=window)<br>txt_edit.grid(<br>    row=<span class="hljs-number">0</span>,<br>    column=<span class="hljs-number">1</span>,<br>    sticky=<span class="hljs-string">&quot;nsew&quot;</span><br>)<br><br><span class="hljs-comment"># 当文本内容改变时，调用count_chars_in_text函数</span><br>txt_edit.config(font=(<span class="hljs-string">&quot;Arial&quot;</span>, <span class="hljs-number">12</span>), undo=<span class="hljs-literal">True</span>, wrap=<span class="hljs-string">&quot;word&quot;</span>)<br>txt_edit.bind(<span class="hljs-string">&quot;&lt;&lt;Modified&gt;&gt;&quot;</span>, count_chars_in_text)  <span class="hljs-comment"># 当文本内容改变时触发事件并调用count_chars_in_text函数</span><br><br><br><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;欢迎使用 notepad 笔记本软件&quot;</span>)<br><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;作者: @Memory&quot;</span>)<br><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;&quot;&quot;  </span><br><span class="hljs-string"> *  </span><br><span class="hljs-string"> (  `  </span><br><span class="hljs-string"> )\))(    (    )       (   (  </span><br><span class="hljs-string">((_)()\  ))\  (     (  )(  )\ )  </span><br><span class="hljs-string">(_()((_)/((_) )\  &#x27; )\(()\(()/(  </span><br><span class="hljs-string">|  \/  (_)) _((_)) ((_)((_))(_))  </span><br><span class="hljs-string">| |\/| / -_) &#x27;  \() _ \ &#x27;_| || |  </span><br><span class="hljs-string">|_|  |_\___|_|_|_|\___/_|  \_, |  </span><br><span class="hljs-string">                           |__/  </span><br><span class="hljs-string">&quot;&quot;&quot;</span>)<br><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;您可以用它来编辑文本文件，也可以快捷地统计文本字数&quot;</span>)<br><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;新的功能还在逐步开发完善中，敬请期待~&quot;</span>)<br><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;您不需要理会这个窗口，祝您使用愉快&quot;</span>)<br><br>window.mainloop()<br></code></pre></td></tr></table></figure>

<ul>
<li>封装后：</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">import</span> tkinter <span class="hljs-keyword">as</span> tk<br><span class="hljs-keyword">import</span> tkinter.filedialog <span class="hljs-keyword">as</span> filedialog<br><br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">MemoryNotepad</span>:<br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span>(<span class="hljs-params">self, window</span>):<br>        self.window = window<br>        self.window.title(<span class="hljs-string">&quot;记事本&quot;</span>)<br>        <span class="hljs-comment"># 读写区</span><br>        self.txt_edit = tk.Text(master=window)<br>        self.txt_edit.grid(<br>            row=<span class="hljs-number">0</span>,<br>            column=<span class="hljs-number">1</span>,<br>            sticky=<span class="hljs-string">&quot;nsew&quot;</span><br>        )<br>        self.btn_frame = tk.Frame(window, bd=<span class="hljs-number">2</span>)<br>        self.btn_frame.grid(row=<span class="hljs-number">0</span>, column=<span class="hljs-number">0</span>, sticky=<span class="hljs-string">&quot;ns&quot;</span>)<br>        self.create_buttons()<br>        <span class="hljs-comment"># 字符数</span><br>        self.var_lbl = tk.StringVar()<br>        self.var_lbl.<span class="hljs-built_in">set</span>(<span class="hljs-string">&quot;&quot;</span>)  <span class="hljs-comment"># 初始化一个空字符串</span><br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">create_buttons</span>(<span class="hljs-params">self</span>):<br>        btn_open = tk.Button(master=self.btn_frame, text=<span class="hljs-string">&quot;打开&quot;</span>, command=self.open_file)<br>        btn_open.grid(row=<span class="hljs-number">0</span>, column=<span class="hljs-number">0</span>, sticky=<span class="hljs-string">&quot;ew&quot;</span>, padx=<span class="hljs-number">5</span>, pady=<span class="hljs-number">5</span>)<br>        btn_save_as = tk.Button(master=self.btn_frame, text=<span class="hljs-string">&quot;另存&quot;</span>, command=self.save_as_file)<br>        btn_save_as.grid(row=<span class="hljs-number">1</span>, column=<span class="hljs-number">0</span>, sticky=<span class="hljs-string">&quot;ew&quot;</span>)<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">open_file</span>(<span class="hljs-params">self</span>):<br>        file_path = filedialog.askopenfilename(<br>            filetypes=[<br>                (<span class="hljs-string">&quot;Text files&quot;</span>, <span class="hljs-string">&quot;*.txt&quot;</span>),<br>                (<span class="hljs-string">&quot;All files&quot;</span>, <span class="hljs-string">&quot;*.*&quot;</span>)<br>            ]<br>        )<br><br>        <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> file_path:<br>            window.title(<span class="hljs-string">&quot;无标题 - 记事本&quot;</span>)<br>            <span class="hljs-keyword">return</span><br><br>        self.txt_edit.delete(<span class="hljs-string">&quot;1.0&quot;</span>, tk.END)<br><br>        <span class="hljs-keyword">with</span> <span class="hljs-built_in">open</span>(<br>                file_path,<br>                mode=<span class="hljs-string">&quot;r&quot;</span>,<br>                encoding=<span class="hljs-string">&quot;utf-8&quot;</span>) <span class="hljs-keyword">as</span> input_file:<br>            self.txt_edit.insert(<br>                tk.END,<br>                input_file.read()<br>            )<br>        window.title(<span class="hljs-string">f&quot;<span class="hljs-subst">&#123;file_path&#125;</span> - 记事本&quot;</span>)<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">save_as_file</span>(<span class="hljs-params">self</span>):<br>        file_path = filedialog.asksaveasfilename(defaultextension=<span class="hljs-string">&quot;.txt&quot;</span>,<br>                                                 filetypes=[(<span class="hljs-string">&quot;Text files&quot;</span>, <span class="hljs-string">&quot;*.txt&quot;</span>), (<span class="hljs-string">&quot;All files&quot;</span>, <span class="hljs-string">&quot;*.*&quot;</span>)])<br>        <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> file_path:<br>            <span class="hljs-keyword">return</span><br>        <span class="hljs-keyword">with</span> <span class="hljs-built_in">open</span>(file_path, mode=<span class="hljs-string">&quot;w&quot;</span>, encoding=<span class="hljs-string">&quot;utf-8&quot;</span>) <span class="hljs-keyword">as</span> output_file:<br>            output_file.write(self.txt_edit.get(<span class="hljs-string">&quot;1.0&quot;</span>, tk.END))<br>        self.window.title(<span class="hljs-string">f&quot;<span class="hljs-subst">&#123;file_path&#125;</span> - 记事本&quot;</span>)<br><br>    <span class="hljs-comment"># 统计字数</span><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">count_chars_in_text</span>(<span class="hljs-params">self</span>):<br>        text = self.txt_edit.get(<span class="hljs-string">&quot;1.0&quot;</span>, tk.END)  <span class="hljs-comment"># 获取 Text 组件中的所有文本</span><br>        char_count = <span class="hljs-built_in">len</span>(text) - <span class="hljs-number">1</span>  <span class="hljs-comment"># 计算文本的长度</span><br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;字符数: <span class="hljs-subst">&#123;char_count&#125;</span>&quot;</span>)<br>        self.var_lbl.<span class="hljs-built_in">set</span>(<span class="hljs-string">f&quot;字符数: <span class="hljs-subst">&#123;char_count&#125;</span>&quot;</span>)  <span class="hljs-comment"># 显示文本</span><br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">init</span>(<span class="hljs-params">self</span>):<br>        self.window.rowconfigure(<br>            <span class="hljs-number">0</span>,<br>            minsize=<span class="hljs-number">100</span>,<br>            weight=<span class="hljs-number">1</span><br>        )<br>        self.window.columnconfigure(<br>            <span class="hljs-number">1</span>,<br>            minsize=<span class="hljs-number">100</span>,<br>            weight=<span class="hljs-number">1</span><br>        )<br><br>        <span class="hljs-comment"># 左侧操作区</span><br>        btn_frame = tk.Frame(<br>            master=self.window,<br>            bd=<span class="hljs-number">2</span><br>        )<br>        btn_frame.grid(<br>            row=<span class="hljs-number">0</span>,<br>            column=<span class="hljs-number">0</span>,<br>            sticky=<span class="hljs-string">&quot;ns&quot;</span><br>        )<br><br>        <span class="hljs-comment"># 打开文本文件</span><br>        btn_open = tk.Button(<br>            master=btn_frame,<br>            text=<span class="hljs-string">&quot;打开&quot;</span>,<br>            command=self.open_file<br>        )<br>        btn_open.grid(<br>            row=<span class="hljs-number">0</span>,<br>            column=<span class="hljs-number">0</span>,<br>            sticky=<span class="hljs-string">&quot;ew&quot;</span>,<br>            padx=<span class="hljs-number">5</span>,<br>            pady=<span class="hljs-number">5</span><br>        )<br><br>        <span class="hljs-comment"># 另存为</span><br>        btn_save_as = tk.Button(<br>            master=btn_frame,<br>            text=<span class="hljs-string">&quot;另存&quot;</span>,<br>            command=self.save_as_file<br>        )<br>        btn_save_as.grid(<br>            row=<span class="hljs-number">1</span>,<br>            column=<span class="hljs-number">0</span>,<br>            sticky=<span class="hljs-string">&quot;ew&quot;</span>,<br>        )<br><br>        <span class="hljs-comment"># 统计字数</span><br>        btn_count = tk.Button(<br>            master=self.window,<br>            text=<span class="hljs-string">&quot;统计字数&quot;</span>,<br>            command=self.count_chars_in_text<br>        )<br>        btn_count.grid(row=<span class="hljs-number">1</span>, column=<span class="hljs-number">1</span>, sticky=<span class="hljs-string">&quot;ew&quot;</span>)<br><br>        lbl = tk.Label(<br>            master=btn_count,<br>            textvariable=self.var_lbl<br>        )<br><br>        lbl.grid(row=<span class="hljs-number">1</span>, column=<span class="hljs-number">1</span>, sticky=<span class="hljs-string">&quot;ew&quot;</span>)<br><br>        <span class="hljs-comment"># 当文本内容改变时，调用count_chars_in_text函数</span><br>        self.txt_edit.config(font=(<span class="hljs-string">&quot;Arial&quot;</span>, <span class="hljs-number">12</span>), undo=<span class="hljs-literal">True</span>, wrap=<span class="hljs-string">&quot;word&quot;</span>)<br>        self.txt_edit.bind(<span class="hljs-string">&quot;&lt;&lt;Modified&gt;&gt;&quot;</span>, self.count_chars_in_text)  <span class="hljs-comment"># 当文本内容改变时触发事件并调用count_chars_in_text函数</span><br><br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;欢迎使用 Memory Notepad 笔记本软件&quot;</span>)<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;作者: @Memory&quot;</span>)<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;&quot;&quot;  </span><br><span class="hljs-string">           *  </span><br><span class="hljs-string">           (  `  </span><br><span class="hljs-string">           )\))(    (    )       (   (  </span><br><span class="hljs-string">          ((_)()\  ))\  (     (  )(  )\ )  </span><br><span class="hljs-string">          (_()((_)/((_) )\  &#x27; )\(()\(()/(  </span><br><span class="hljs-string">          |  \/  (_)) _((_)) ((_)((_))(_))  </span><br><span class="hljs-string">          | |\/| / -_) &#x27;  \() _ \ &#x27;_| || |  </span><br><span class="hljs-string">          |_|  |_\___|_|_|_|\___/_|  \_, |  </span><br><span class="hljs-string">                                     |__/  </span><br><span class="hljs-string">          &quot;&quot;&quot;</span>)<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;您可以用它来编辑文本文件，也可以快捷地统计文本字数&quot;</span>)<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;新的功能还在逐步开发完善中，敬请期待~&quot;</span>)<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;您不需要理会这个窗口，祝您使用愉快&quot;</span>)<br><br>        self.window.mainloop()<br><br><br><span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">&#x27;__main__&#x27;</span>:<br>    window = tk.Tk()<br>    memoryNotepad = MemoryNotepad(window)<br>    memoryNotepad.init()<br><br></code></pre></td></tr></table></figure>

<ul>
<li>整个改造过程中，最重要的是把需要初始化的资源 / 变量都放在构造函数中完成，如下：</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span>(<span class="hljs-params">self, window</span>):<br>    self.window = window<br>    self.window.title(<span class="hljs-string">&quot;记事本&quot;</span>)<br>    <span class="hljs-comment"># 读写区</span><br>    self.txt_edit = tk.Text(master=window)<br>    self.txt_edit.grid(<br>        row=<span class="hljs-number">0</span>,<br>        column=<span class="hljs-number">1</span>,<br>        sticky=<span class="hljs-string">&quot;nsew&quot;</span><br>    )<br>    self.btn_frame = tk.Frame(window, bd=<span class="hljs-number">2</span>)<br>    self.btn_frame.grid(row=<span class="hljs-number">0</span>, column=<span class="hljs-number">0</span>, sticky=<span class="hljs-string">&quot;ns&quot;</span>)<br>    self.create_buttons()<br>    <span class="hljs-comment"># 字符数</span><br>    self.var_lbl = tk.StringVar()<br>    self.var_lbl.<span class="hljs-built_in">set</span>(<span class="hljs-string">&quot;&quot;</span>)  <span class="hljs-comment"># 初始化一个空字符串</span><br></code></pre></td></tr></table></figure>

<ul>
<li>虽然之前学过 Python 基础语法，现在写还是有些生疏，慢慢习惯吧，还是很简单的<strong>（2023/12/04晚）</strong></li>
<li>遗留下了问题：</li>
</ul>
<p><img src="https://gitee.com/deng-2022/pictures/raw/master/images/image-20231204222014864.png" alt="image-20231204222014864"></p>
<ul>
<li><p>如上，在主函数引入 MemoryNotepad 类，点击 “开始使用”后，直接跳出 “记事本” 窗口，明天再研究吧</p>
</li>
<li><p>继续<strong>（2023/12/08午）</strong></p>
</li>
<li><p>怪了，明明写了有参构造器，new 一个对象还报错：</p>
</li>
</ul>
<p><img src="https://gitee.com/deng-2022/pictures/raw/master/images/image-20231208165645504.png" alt="image-20231208165645504"></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">class</span> <span class="hljs-title class_">MemoryTranslator</span>:<br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">__int__</span>(<span class="hljs-params">self, root</span>):<br>        self.root = root<br>        <span class="hljs-comment"># Create the main window with two text boxes and a button</span><br>        self.root.title(<span class="hljs-string">&quot;Translation App&quot;</span>)<br>        self.root.geometry(<span class="hljs-string">&quot;600x300&quot;</span>)<br></code></pre></td></tr></table></figure>

<ul>
<li>哦他奶奶的， <code>__init__ </code> 写成 <code> __int__</code> 了</li>
</ul>
<figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><code class="hljs routeros">self.window = tk.Tk()<br>      self.window.title(<span class="hljs-string">&quot;记事本&quot;</span>)<br><br>      # 创建操作区(左层）<br>      self.operate_frame = tk.Frame(self.window)<br>      # top_frame.grid()<br>      self.operate_frame.pack(<span class="hljs-attribute">side</span>=tk.LEFT, <span class="hljs-attribute">fill</span>=tk.BOTH, <span class="hljs-attribute">expand</span>=<span class="hljs-literal">True</span>)<br><br>      # 创建读写区(右层)<br>      self.io_frame = tk.Frame(self.window)<br>      self.io_frame.pack(<span class="hljs-attribute">side</span>=tk.LEFT, <span class="hljs-attribute">fill</span>=tk.BOTH, <span class="hljs-attribute">expand</span>=<span class="hljs-literal">True</span>)<br><br>      # 创建计数区(下层)<br>      self.count_frame = tk.Frame(self.window)<br>      self.count_frame.pack(<span class="hljs-attribute">side</span>=tk.BOTTOM, <span class="hljs-attribute">fill</span>=tk.BOTH, <span class="hljs-attribute">expand</span>=<span class="hljs-literal">True</span>)<br><br>      # 文字编辑<br>      self.txt_edit = tk.Text(<span class="hljs-attribute">master</span>=self.io_frame)<br>      self.txt_edit.pack(<span class="hljs-attribute">side</span>=tk.RIGHT)<br><br>      self.window.rowconfigure(0, <span class="hljs-attribute">minsize</span>=100, <span class="hljs-attribute">weight</span>=1)<br>      self.window.columnconfigure(1, <span class="hljs-attribute">minsize</span>=100, <span class="hljs-attribute">weight</span>=1)<br><br>      # 打开按钮<br>      btn_open = tk.Button(<span class="hljs-attribute">master</span>=self.operate_frame, <span class="hljs-attribute">text</span>=<span class="hljs-string">&quot;打开&quot;</span>, <span class="hljs-attribute">command</span>=self.open_file)<br>      btn_open.pack()<br><br>      # 另存为按钮<br>      btn_save_as = tk.Button(<span class="hljs-attribute">master</span>=self.operate_frame, <span class="hljs-attribute">text</span>=<span class="hljs-string">&quot;另存&quot;</span>, <span class="hljs-attribute">command</span>=self.save_as_file)<br>      btn_save_as.pack()<br><br>      # 统计字数按钮<br>      btn_count = tk.Button(<span class="hljs-attribute">master</span>=self.window, <span class="hljs-attribute">text</span>=<span class="hljs-string">&quot;统计字数&quot;</span>, <span class="hljs-attribute">command</span>=self.count_chars_in_text)<br>      btn_count.pack()<br><br>      # 字符数标签<br>      self.var_lbl = tk.StringVar()<br>      self.var_lbl.<span class="hljs-built_in">set</span>(<span class="hljs-string">&quot;&quot;</span>)  # 初始化一个空字符串<br>      lbl = tk.Label(<span class="hljs-attribute">master</span>=btn_count, <span class="hljs-attribute">textvariable</span>=self.var_lbl)<br>      lbl.pack()<br><br>      # 当文本内容改变时，调用count_chars_in_text函数<br>      self.txt_edit.config(font=(<span class="hljs-string">&quot;Arial&quot;</span>, 12), <span class="hljs-attribute">undo</span>=<span class="hljs-literal">True</span>, <span class="hljs-attribute">wrap</span>=<span class="hljs-string">&quot;word&quot;</span>)<br>      self.txt_edit.bind(<span class="hljs-string">&quot;&lt;&lt;Modified&gt;&gt;&quot;</span>, self.count_chars_in_text)  # 当文本内容改变时触发事件并调用count_chars_in_text函数<br></code></pre></td></tr></table></figure>

<h3 id="一个折磨人的BUG"><a href="#一个折磨人的BUG" class="headerlink" title="一个折磨人的BUG"></a>一个折磨人的BUG</h3><ul>
<li>就很简单的实现：按钮绑定函数，点击按钮，执行该函数<strong>（2023/12/08晚）</strong></li>
<li>现在的问题很诡异，实例化一个对象，直接创建窗口；点击按钮，不触发生成窗口函数</li>
<li>看看这段奇怪的代码：</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">class</span> <span class="hljs-title class_">MemoryNotepad</span>:<br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span>(<span class="hljs-params">self</span>):<br>        self.window1 = tk.Tk()<br>        self.window1.title(<span class="hljs-string">&quot;记事本&quot;</span>)<br>        <span class="hljs-comment"># self.window.mainloop()</span><br><br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">MemoryTools</span>:<br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span>(<span class="hljs-params">self</span>):<br>        self.window2 = tk.Tk()<br>        self.window2.title(<span class="hljs-string">&quot;MemoryTools&quot;</span>)<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">create_window</span>(<span class="hljs-params">self</span>):<br>        mn = MemoryNotepad()<br>        self.window2.mainloop()<br><br><br><span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">&#x27;__main__&#x27;</span>:<br>    mt = MemoryTools()<br>    mt.create_window()<br></code></pre></td></tr></table></figure>

<p><img src="https://gitee.com/deng-2022/pictures/raw/master/images/image-20231208211539507.png" alt="image-20231208211539507"></p>
<h3 id="BUG-解决"><a href="#BUG-解决" class="headerlink" title="BUG 解决"></a>BUG 解决</h3><ul>
<li>整整一周过去了，这个烦人的 BUG 终于解决了</li>
<li>这其实是 <code>tkinter</code> 的渲染问题，在类 <code>MemoryNotepad</code> 的 <code>__init__</code> 函数中写如下代码：</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">class</span> <span class="hljs-title class_">MemoryNotepad</span>:<br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span>(<span class="hljs-params">self</span>):<br>        self.window = tk.Tk()<br>          self.window.title(<span class="hljs-string">&quot;MemoryNotepad&quot;</span>)<br></code></pre></td></tr></table></figure>

<ul>
<li>在类 <code>MemoryTools</code> 的 <code>__init__</code> 函数中写如下代码：</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">class</span> <span class="hljs-title class_">MemoryTools</span>:<br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span>(<span class="hljs-params">self</span>):<br>        self.window = tk.Tk()<br>        self.window.title(<span class="hljs-string">&quot;MemoryTools&quot;</span>)<br><br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">create_window</span>(<span class="hljs-params">self</span>):<br>        mn = MemoryNotepad()<br>        self.window.mainloop()<br></code></pre></td></tr></table></figure>

<ul>
<li>接着实例化一个  <code>MemoryTools</code> 对象，并调用 <code>create_window</code> 方法：</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">&#x27;__main__&#x27;</span>:<br>    mt = MemoryTools()<br>    mt.create_window() <br></code></pre></td></tr></table></figure>

<ul>
<li>可以看到，在 <code>create_window</code> 方法中，实例化了一个 <code>MemoryNotepad</code> 对象，并执行生成了一个窗口</li>
<li><code>title</code> 为 <code>MemoryTools</code> 的窗口被被执行生成是很正确的，但是 <code>title</code>  为 <code>MemoryNotepad</code> 的窗口也被执行生成了：</li>
</ul>
<p><img src="https://gitee.com/deng-2022/pictures/raw/master/images/image-20231210114439198.png" alt="image-20231210114439198"></p>
<ul>
<li>这就非常奇怪了，明明没有显示地执行生成<code>title</code>  为 <code>MemoryNotepad</code> 的窗口，它却自动生成窗口了，这个机制很奇怪</li>
<li>引发了很棘手的问题：实现点击 <code>button</code> 按钮后，执行生成新窗口实现不了，因为实例化新窗口之后，就自动生成新窗口了</li>
<li>几经折腾，总算找到了解决的办法：</li>
<li>问题的根源在于我尝试在 <code>__init__</code> 函数中，初始化一个窗口对象 <code>window</code>，只要把 <code>window</code> 的初始化，推迟到初始化函数中就行了，无需在<code> __init__</code> 中初始化，因为这个机制只会影响到 <code> __init__</code> 内的 <code>window</code> 窗口对象的生成</li>
<li>于是改写后的 <code>MemoryNotepad</code> 如下：</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">class</span> <span class="hljs-title class_">MemoryNotepad</span>:<br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span>(<span class="hljs-params">self</span>):<br>        self.window = <span class="hljs-literal">None</span><br>        <span class="hljs-comment"># 左侧操作区</span><br>        self.operate_frame = <span class="hljs-literal">None</span><br>        <span class="hljs-comment"># 打开按钮</span><br>        self.btn_open = <span class="hljs-literal">None</span><br>        <span class="hljs-comment"># 另存为按钮</span><br>        self.btn_save_as = <span class="hljs-literal">None</span><br>        <span class="hljs-comment"># 统计字数按钮</span><br>        self.btn_count = <span class="hljs-literal">None</span><br>        <span class="hljs-comment"># 文字编辑区</span><br>        self.txt_edit = <span class="hljs-literal">None</span><br>        <span class="hljs-comment"># 初始化字符数</span><br>        self.var_lbl = <span class="hljs-literal">None</span><br>        <span class="hljs-comment"># 字符数标签</span><br>        self.lbl = <span class="hljs-literal">None</span><br></code></pre></td></tr></table></figure>

<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs python">  <span class="hljs-keyword">def</span> <span class="hljs-title function_">init</span>(<span class="hljs-params">self</span>):<br>      self.window = tk.Tk()<br>      self.window.title(<span class="hljs-string">&quot;记事本&quot;</span>)<br>      <span class="hljs-comment"># 左侧操作区</span><br>      self.operate_frame = tk.Frame(master=self.window, bd=<span class="hljs-number">2</span>)<br>      self.operate_frame.grid(row=<span class="hljs-number">0</span>, column=<span class="hljs-number">0</span>, sticky=<span class="hljs-string">&quot;ns&quot;</span>)<br>      <span class="hljs-comment"># 窗口大小不可变</span><br>      self.window.rowconfigure(<span class="hljs-number">0</span>, minsize=<span class="hljs-number">100</span>, weight=<span class="hljs-number">1</span>)<br>      self.window.columnconfigure(<span class="hljs-number">1</span>, minsize=<span class="hljs-number">100</span>, weight=<span class="hljs-number">1</span>)<br>...............................<br></code></pre></td></tr></table></figure>

<ul>
<li>成功实现了点击 <code>简易笔记本</code> 按钮后，弹出窗口：</li>
</ul>
<p><img src="https://gitee.com/deng-2022/pictures/raw/master/images/image-20231210114706146.png" alt="image-20231210114706146"></p>
<h3 id="整合所有功能"><a href="#整合所有功能" class="headerlink" title="整合所有功能"></a>整合所有功能</h3><ul>
<li>整合 AI 对话模块时，出错了，由于 <code>python</code> 环境不同，同样的代码还运行不起来，改下 <code>MemoryTools</code> 的 <code>python</code> 环境变量即可：</li>
</ul>
<p><img src="C:\Users\Lenovo\AppData\Roaming\Typora\typora-user-images\image-20231210205845871.png" alt="image-20231210205845871"></p>
<ul>
<li>改完记得要重启啊，不重启没效果的，运行成功：</li>
</ul>
<p><img src="C:\Users\Lenovo\AppData\Roaming\Typora\typora-user-images\image-20231210205939054.png" alt="image-20231210205939054"></p>
<ul>
<li>终于把 AIChat 类改装好了，改装过程中，最需要注意的就是成员函数的参数形式了：</li>
</ul>
<blockquote>
<p>如果成员函数内部需要引用到成员变量，就把该成员函数的第一个参数指定为 <code>self</code></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">def</span> <span class="hljs-title function_">main</span>(<span class="hljs-params">self, appid, api_key, api_secret, Spark_url, domain, question</span>):<br>      <span class="hljs-comment"># print(&quot;星火:&quot;)</span><br>      wsParam = Ws_Param(appid, api_key, api_secret, Spark_url)<br>      <span class="hljs-comment"># websocket.enableTrace(False)</span><br>      wsUrl = wsParam.create_url()<br>      ws = websocket.WebSocketApp(wsUrl, on_message=self.on_message, on_error=self.on_error, on_close=self.on_close,<br>                                  on_open=self.on_open)<br>      ws.appid = appid<br>      ws.question = question<br>      ws.domain = domain<br>      ws.run_forever(sslopt=&#123;<span class="hljs-string">&quot;cert_reqs&quot;</span>: ssl.CERT_NONE&#125;)<br></code></pre></td></tr></table></figure>

<p>反之，就在成员函数定义上方添加这样的注解：<code>@staticmethod</code></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-meta">@staticmethod</span><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">getlength</span>(<span class="hljs-params">text</span>):<br>    length = <span class="hljs-number">0</span><br>    <span class="hljs-keyword">for</span> content <span class="hljs-keyword">in</span> text:<br>        temp = content[<span class="hljs-string">&quot;content&quot;</span>]<br>        leng = <span class="hljs-built_in">len</span>(temp)<br>        length += leng<br>    <span class="hljs-keyword">return</span> length<br></code></pre></td></tr></table></figure>

</blockquote>
<h3 id="开发者文档插入图片"><a href="#开发者文档插入图片" class="headerlink" title="开发者文档插入图片"></a>开发者文档插入图片</h3><ul>
<li>上传至 Gitee 图床，在开发者文档中不显示，只好是放进文件夹中了，像这样：<strong>（2023/12/14晚）</strong></li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><code class="hljs vue">## 效果演示<br><br>- 打开软件<br><br>&lt;img :src=&quot;$withBase(&#x27;/img/article/image-20231214000036004.png&#x27;)&quot;   class=&quot;no-zoom&quot; style=&quot;margin: 10px;&quot;&gt;<br><br>- 你可以点击 &quot;打开&quot; 按钮，选取并打开本地的文本文件<br><br>&lt;img :src=&quot;$withBase(&#x27;/img/article/image-20231214001301049.png&#x27;)&quot;   class=&quot;no-zoom&quot; style=&quot;margin: 10px;&quot;&gt;<br><br>&lt;img :src=&quot;$withBase(&#x27;/img/article/image-20231214001336235.png&#x27;)&quot;   class=&quot;no-zoom&quot; style=&quot;margin: 10px;&quot;&gt;<br><br>&lt;img :src=&quot;$withBase(&#x27;/img/article/image-20231214001417352.png&#x27;)&quot;   class=&quot;no-zoom&quot; style=&quot;margin: 10px;&quot;&gt;<br><br>- 点击 &quot;另存&quot; 按钮，可将右侧文本框中的文本内容保存至本地<br><br>&lt;img :src=&quot;$withBase(&#x27;/img/article/image-20231214001732669.png&#x27;)&quot;  class=&quot;no-zoom&quot; style=&quot;margin: 10px;&quot;&gt;<br><br>&lt;img :src=&quot;$withBase(&#x27;/img/article/image-20231214001743210.png&#x27;)&quot;  class=&quot;no-zoom&quot; style=&quot;margin: 10px;&quot;&gt;<br><br>- 附带功能：快捷统计文本字数<br><br>&lt;img :src=&quot;$withBase(&#x27;/img/article/image-20231214002003689.png&#x27;)&quot;   class=&quot;no-zoom&quot; style=&quot;margin: 10px;&quot;&gt;<br></code></pre></td></tr></table></figure>

<p><img src="C:\Users\Lenovo\AppData\Roaming\Typora\typora-user-images\image-20231214213905452.png" alt="image-20231214213905452"></p>
<h3 id="窗口填充图片"><a href="#窗口填充图片" class="headerlink" title="窗口填充图片"></a>窗口填充图片</h3><ul>
<li>在窗口中填充一张图片作为背景：</li>
<li>导入相关库：</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">import</span> tkinter <span class="hljs-keyword">as</span> tk<br><span class="hljs-keyword">from</span> PIL <span class="hljs-keyword">import</span> Image, ImageTk<br></code></pre></td></tr></table></figure>

<ul>
<li>准备图片，并确保导入路径正确：</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span>(<span class="hljs-params">self</span>):<br>    <span class="hljs-comment"># 创建主窗口</span><br>    self.window = tk.Tk()<br>    self.window.geometry(<span class="hljs-string">&quot;300x225&quot;</span>)<br>    self.window.title(<span class="hljs-string">&quot;开始菜单&quot;</span>)<br><br>    <span class="hljs-comment"># 加载背景图片</span><br>    image = Image.<span class="hljs-built_in">open</span>(<span class="hljs-string">&quot;D:\\Project\\星球项目\\MemoryTools\\imgs\\mountain2.jpg&quot;</span>)<br>    bg_image = ImageTk.PhotoImage(image)<br><br>    <span class="hljs-comment"># 创建标签并设置背景图片</span><br>    bg_label = tk.Label(self.window, image=bg_image)<br>    bg_label.pack(fill=tk.BOTH, expand=<span class="hljs-literal">True</span>)<br></code></pre></td></tr></table></figure>

<p><img src="https://gitee.com/deng-2022/pictures/raw/master/images/image-20231218082934745.png" alt="image-20231218082934745"></p>
<ul>
<li>然而这样是会报错的：</li>
</ul>
<p><img src="https://gitee.com/deng-2022/pictures/raw/master/images/image-20231218083051347.png" alt="image-20231218083051347"></p>
<ul>
<li>原因如下：</li>
</ul>
<blockquote>
<p>图片格式不受支持：<code>Tkinter</code> 的 <code>PhotoImage</code> 类只支持 <code>GIF</code>、<code>PPM/PGM</code> 格式的图片。对于 <code>JPEG</code>、<code>PNG</code> 等其他格式的图片，你需要使用 <code>PIL（Python Imaging Library）库</code>来进行处理。你可以尝试将你的 <code>JPEG</code> 图片转换为 <code>GIF</code> 或<code> PPM/PGM 格式</code>，或者你可以使用 <code>PIL 库</code>来加载 JPEG 图片。</p>
</blockquote>
<ul>
<li>我们尝试使用  <code>Image</code>、 <code>ImageTk</code> 解决问题：</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">import</span> tkinter <span class="hljs-keyword">as</span> tk<br><span class="hljs-keyword">from</span> PIL <span class="hljs-keyword">import</span> Image, ImageTk<br><br>window = tk.Tk()<br><span class="hljs-comment"># window.geometry(&quot;300x225&quot;)</span><br>window.title(<span class="hljs-string">&quot;开始菜单&quot;</span>)<br><br><span class="hljs-comment"># 加载背景图片</span><br>image = Image.<span class="hljs-built_in">open</span>(<span class="hljs-string">&quot;D:\\Project\\星球项目\\MemoryTools\\imgs\\mountain2.jpg&quot;</span>)<br>bg_image = ImageTk.PhotoImage(image)<br><br><span class="hljs-comment"># 创建标签并设置背景图片</span><br>bg_label = tk.Label(window, image=bg_image)<br>bg_label.pack(fill=tk.BOTH, expand=<span class="hljs-literal">True</span>)<br><br>window.mainloop()<br></code></pre></td></tr></table></figure>

<ul>
<li>设置背景图片成功，需要注意设置原背景图的尺寸<strong>（2023/12/18早）</strong></li>
</ul>
<p><img src="https://gitee.com/deng-2022/pictures/raw/master/images/image-20231218083431150.png" alt="image-20231218083431150"></p>
<ul>
<li>尝试改造 <code>MemoryTools</code> 的开始菜单页面：</li>
<li>填充背景图片，并适当调整<strong>窗口大小</strong>和<strong>图片大小</strong>：<strong>（2023/12/18早）</strong></li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span>(<span class="hljs-params">self</span>):<br>    <span class="hljs-comment"># 创建主窗口</span><br>    self.window = tk.Tk()<br>    self.window.geometry(<span class="hljs-string">&quot;620x350&quot;</span>)<br>    self.window.title(<span class="hljs-string">&quot;Memory Tools&quot;</span>)<br>    <span class="hljs-comment"># 设置窗口大小禁止改变</span><br>    self.window.resizable(<span class="hljs-literal">False</span>, <span class="hljs-literal">False</span>)<br><br>    <span class="hljs-comment"># 加载背景图片</span><br>    self.image = Image.<span class="hljs-built_in">open</span>(<span class="hljs-string">&quot;D:\\Project\\星球项目\\MemoryTools\\imgs\\mountain2.jpg&quot;</span>)<br>    <span class="hljs-comment"># 调整图片尺寸</span><br>    self.image = self.image.resize((<span class="hljs-number">620</span>, <span class="hljs-number">350</span>))  <span class="hljs-comment"># 这里的100是目标宽度和高度，你可以根据需要修改</span><br>    <span class="hljs-comment"># 转 JEPG 格式为 PPM/PGM 格式</span><br>    self.bg_image = ImageTk.PhotoImage(self.image)<br></code></pre></td></tr></table></figure>

<ul>
<li>添加一个标签组件 <code>label</code> 和一个按钮组件 <code>button</code> ，调整它们的显示方式，使其<strong>自由浮动于该图片之上</strong>：</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-comment"># 在上层Frame中添加一个标签</span><br>self.label = tk.Label(self.window, text=<span class="hljs-string">&quot;欢迎使用 Memery Tools！&quot;</span>, font=(<span class="hljs-string">&quot;Arial&quot;</span>, <span class="hljs-number">16</span>))<br><br><span class="hljs-comment"># 使用place()方法将标签放置在窗口的左上角，并设置宽度和高度为窗口的相对大小</span><br>self.label.place(x=<span class="hljs-number">200</span>, y=<span class="hljs-number">60</span>)<br></code></pre></td></tr></table></figure>

<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-comment"># 在下层Frame中添加按钮</span><br>self.button = tk.Button(self.window, text=<span class="hljs-string">&quot;开始使用&quot;</span>, font=(<span class="hljs-string">&quot;Arial&quot;</span>, <span class="hljs-number">12</span>), width=<span class="hljs-number">10</span>, height=<span class="hljs-number">2</span>,<br>command=<span class="hljs-keyword">lambda</span>: self.create_menu_window(self.window))<br><br><span class="hljs-comment"># self.button.pack()</span><br>self.button.place(x=<span class="hljs-number">270</span>, y=<span class="hljs-number">250</span>)  <span class="hljs-comment"># 设置按钮的位置，这里的坐标是相对于窗口的左上角</span><br></code></pre></td></tr></table></figure>

<ul>
<li><strong>改造成功</strong>！效果如下：</li>
</ul>
<p><img src="https://gitee.com/deng-2022/pictures/raw/master/images/image-20231218085414790.png" alt="image-20231218085414790"></p>
<ul>
<li>上午我们实现了<strong>开始菜单页面</strong>的<strong>背景图填充</strong>，晚上我们继续完成<strong>工具栏页面</strong>的<strong>背景图填充</strong>：</li>
</ul>
<p><img src="https://gitee.com/deng-2022/pictures/raw/master/images/image-20231219000023787.png" alt="image-20231219000023787"></p>
<h3 id="项目打包后图片路径丢失"><a href="#项目打包后图片路径丢失" class="headerlink" title="项目打包后图片路径丢失"></a>项目打包后图片路径丢失</h3><blockquote>
<p>🍖 推荐阅读：</p>
<ul>
<li></li>
</ul>
</blockquote>
<ul>
<li>我在项目中引用了图片：<strong>（2023/12/20晚）</strong></li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-comment"># 加载背景图片</span><br>self.image = Image.<span class="hljs-built_in">open</span>(<span class="hljs-string">&quot;imgs/mountain2.jpg&quot;</span>)<br><span class="hljs-comment"># 调整图片尺寸</span><br>self.image = self.image.resize((<span class="hljs-number">620</span>, <span class="hljs-number">350</span>))  <span class="hljs-comment"># 这里的100是目标宽度和高度，你可以根据需要修改</span><br><span class="hljs-comment"># 转 JEPG 格式为 PPM/PGM 格式</span><br>self.bg_image = ImageTk.PhotoImage(self.image)<br><br><span class="hljs-comment"># 创建标签并设置背景图片</span><br>self.bg_label = tk.Label(self.window, image=self.bg_image)<br>self.bg_label.pack(fill=tk.BOTH, expand=<span class="hljs-literal">True</span>)<br></code></pre></td></tr></table></figure>

<ul>
<li>这里的图片路径很关键，如果是绝对路径，<code>pyinstaller</code> 打包后，直接双击.exe文件会直接报错</li>
<li>我只好按图片路径，在打包完成后，手动添加图片资源路径：</li>
</ul>
<p><img src="https://gitee.com/deng-2022/pictures/raw/master/images/image-20231220135409789.png" alt="image-20231220135409789"></p>
<h3 id="点击按钮改变标签内容"><a href="#点击按钮改变标签内容" class="headerlink" title="点击按钮改变标签内容"></a>点击按钮改变标签内容</h3><ul>
<li>点击按钮，实现改变指定标签 <code>lable</code> 的内容</li>
<li>这里实际的业务要求是标签根据文本框中的内容是否发生改变，记录此时的字符并绑定该值到标签 <code>lable</code> 上</li>
<li>这是之前的实现方式：</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-comment"># 统计字符数量</span><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">count_chars_in_text</span>(<span class="hljs-params">self</span>):<br>    <span class="hljs-comment"># 获取 Text 组件中的所有文本</span><br>    text = self.txt_edit.get(<span class="hljs-string">&quot;1.0&quot;</span>, tk.END)<br>    <span class="hljs-comment"># 计算文本的长度</span><br>    char_count = <span class="hljs-built_in">len</span>(text) - <span class="hljs-number">1</span><br><br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;字符数: <span class="hljs-subst">&#123;char_count&#125;</span>&quot;</span>)<br>    <span class="hljs-comment"># 显示文本</span><br>    self.var_lbl.<span class="hljs-built_in">set</span>(<span class="hljs-string">f&quot;字符数: <span class="hljs-subst">&#123;char_count&#125;</span>&quot;</span>)<br></code></pre></td></tr></table></figure>

<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-comment"># 统计字数按钮</span><br>self.btn_count = tk.Button(master=self.window, text=<span class="hljs-string">&quot;统计字数&quot;</span>, command=self.count_chars_in_text)<br>self.btn_count.grid(row=<span class="hljs-number">1</span>, column=<span class="hljs-number">1</span>, sticky=<span class="hljs-string">&quot;ew&quot;</span>)<br><br><span class="hljs-comment"># 初始化字符数</span><br>self.var_lbl = tk.StringVar()<br> <span class="hljs-comment"># 初始化一个空字符串</span><br>self.var_lbl.<span class="hljs-built_in">set</span>(<span class="hljs-string">&quot;&quot;</span>) <br><br><span class="hljs-comment"># 字符数标签</span><br>self.lbl = tk.Label(master=self.btn_count, textvariable=self.var_lbl)<br>self.lbl.grid(row=<span class="hljs-number">1</span>, column=<span class="hljs-number">1</span>, sticky=<span class="hljs-string">&quot;ew&quot;</span>)<br><br><span class="hljs-comment"># 监听文本内容改变</span><br>self.txt_edit.config(font=(<span class="hljs-string">&quot;Arial&quot;</span>, <span class="hljs-number">12</span>), undo=<span class="hljs-literal">True</span>, wrap=<span class="hljs-string">&quot;word&quot;</span>)<br><span class="hljs-comment"># 当文本内容改变时触发事件并调用count_chars_in_text函数</span><br>self.txt_edit.bind(<span class="hljs-string">&quot;&lt;&lt;Modified&gt;&gt;&quot;</span>, self.count_chars_in_text)<br></code></pre></td></tr></table></figure>

<ul>
<li><p>但是这里有个奇怪的问题：<code>label</code> 标签加上 <code>textvariable</code> 属性，在外部调用该 <code>label</code> 所在函数，<code>label</code> 标签不显示</p>
</li>
<li><p>我使用了新的方案解决这个问题：不使用 <code>textvariable</code> 属性，使用简单的 <code>text</code> 属性解决这个问题：</p>
</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-comment"># 统计字符数量</span><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">count_chars_in_text</span>(<span class="hljs-params">self</span>):<br>    <span class="hljs-comment"># 获取 Text 组件中的所有文本</span><br>    text = self.txt_edit.get(<span class="hljs-string">&quot;1.0&quot;</span>, tk.END)<br>    <span class="hljs-comment"># 计算文本的长度</span><br>    char_count = <span class="hljs-built_in">len</span>(text) - <span class="hljs-number">1</span><br><br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;字符数: <span class="hljs-subst">&#123;char_count&#125;</span>&quot;</span>)<br>    <span class="hljs-comment"># 修改字符串变量的值</span><br>    self.var_lbl = <span class="hljs-string">f&quot;字符数: <span class="hljs-subst">&#123;char_count&#125;</span>&quot;</span><br>    self.update_label()  <span class="hljs-comment"># 更新Label的文本为新的值</span><br>    <span class="hljs-comment"># self.var_lbl.set(f&quot;字符数: &#123;char_count&#125;&quot;)</span><br></code></pre></td></tr></table></figure>

<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-comment"># 更新 Label 的文本的值</span><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">update_label</span>(<span class="hljs-params">self</span>):<br>    <span class="hljs-comment"># 更新Label的文本为当前的字符串变量的值</span><br>    self.lbl.config(text=self.var_lbl)<br>    <span class="hljs-comment"># 更新显示</span><br>    self.lbl.update()<br></code></pre></td></tr></table></figure>

<figure class="highlight py"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs py"><span class="hljs-comment"># 字符数标签</span><br>self.lbl = tk.Label(master=self.btn_count)<br>self.lbl.grid(row=<span class="hljs-number">1</span>, column=<span class="hljs-number">1</span>, sticky=<span class="hljs-string">&quot;ew&quot;</span>)<br><br><span class="hljs-comment"># 创建一个可变的字符串变量</span><br>self.var_lbl = <span class="hljs-string">&quot;初始文本&quot;</span><br>self.update_label()<br><br><span class="hljs-comment"># 监听文本内容改变</span><br>self.txt_edit.config(font=(<span class="hljs-string">&quot;Arial&quot;</span>, <span class="hljs-number">12</span>), undo=<span class="hljs-literal">True</span>, wrap=<span class="hljs-string">&quot;word&quot;</span>)<br><span class="hljs-comment"># 当文本内容改变时触发事件并调用count_chars_in_text函数</span><br>self.txt_edit.bind(<span class="hljs-string">&quot;&lt;&lt;Modified&gt;&gt;&quot;</span>, self.count_chars_in_text)<br></code></pre></td></tr></table></figure>

<ul>
<li>不同的实现方法，完全一样的效果<strong>（2023/12/20晚）</strong></li>
</ul>
<h2 id="日常报错"><a href="#日常报错" class="headerlink" title="日常报错"></a>日常报错</h2><h3 id="修改-pip-命令镜像源"><a href="#修改-pip-命令镜像源" class="headerlink" title="修改 pip 命令镜像源"></a>修改 pip 命令镜像源</h3><ul>
<li><p>Python 下载 / 引入包失败，<strong>改变镜像源</strong>可能会解决这个问题：<strong>（2023/10/18午）</strong></p>
</li>
<li><h5 id="windows环境pip设置国内源-pip国内源-t梧桐树t的博客-CSDN博客"><a href="#windows环境pip设置国内源-pip国内源-t梧桐树t的博客-CSDN博客" class="headerlink" title="windows环境pip设置国内源_pip国内源_t梧桐树t的博客-CSDN博客"></a><a target="_blank" rel="noopener" href="https://blog.csdn.net/winerpro/article/details/131009816">windows环境pip设置国内源_pip国内源_t梧桐树t的博客-CSDN博客</a></h5></li>
<li><p>有可能是网络原因，修改镜像源以保证 pip 得以正常引入包</p>
</li>
</ul>
<figure class="highlight awk"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs awk">pip install pygame -i https:<span class="hljs-regexp">//</span>pypi.tuna.tsinghua.edu.cn<span class="hljs-regexp">/simple/</span><br></code></pre></td></tr></table></figure>

<h1 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h1>
                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/memory_blog/categories/Python/" class="category-chain-item">Python</a>
  
  
    <span>></span>
    
  <a href="/memory_blog/categories/Python/%E7%88%AC%E8%99%AB/" class="category-chain-item">爬虫</a>
  
  
    <span>></span>
    
  <a href="/memory_blog/categories/Python/%E7%88%AC%E8%99%AB/%E6%95%B0%E6%8D%AE%E5%A4%84%E7%90%86/" class="category-chain-item">数据处理</a>
  
  

  

  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/memory_blog/tags/%E5%BC%80%E5%8F%91%E7%BB%8F%E9%AA%8C/">#开发经验</a>
      
        <a href="/memory_blog/tags/%E7%88%AC%E8%99%AB/">#爬虫</a>
      
        <a href="/memory_blog/tags/Python/">#Python</a>
      
        <a href="/memory_blog/tags/%E6%95%B0%E6%8D%AE%E5%A4%84%E7%90%86/">#数据处理</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>探索Python爬虫的无限可能性：基础与应用</div>
      <div>https://test.atomgit.net/memory_blog/2023/05/21/探索 Python 爬虫的无限可能性：基础与应用/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>Memory</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2023年5月21日</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>更新于</div>
          <div>2023年12月20日</div>
        </div>
      
      
        <div class="license-meta-item">
          <div>许可协议</div>
          <div>
            
              
              
                <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
                  <span class="hint--top hint--rounded" aria-label="BY - 署名">
                    <i class="iconfont icon-by"></i>
                  </span>
                </a>
              
            
          </div>
        </div>
      
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/memory_blog/2023/05/27/%E5%A4%A7%E9%81%93%E8%87%B3%E7%AE%80%EF%BC%9A%E5%BF%AB%E9%80%9F%E6%90%AD%E5%BB%BA%E5%8D%9A%E5%AE%A2%E4%B8%8E%E6%96%87%E6%A1%A3%E7%AB%99%E7%82%B9%E7%9A%84%E7%BB%88%E6%9E%81%E6%8C%87%E5%8D%971.0/" title="大道至简：快速搭建博客与文档站点的终极指南1.0">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">大道至简：快速搭建博客与文档站点的终极指南1.0</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/memory_blog/2023/04/22/%E9%A1%B9%E7%9B%AE%E5%9B%9E%E9%A1%BE%20-%20%E5%AE%9E%E8%B7%B5%E7%BB%8F%E9%AA%8C%E5%92%8C%E6%94%B6%E8%8E%B7%E6%80%BB%E7%BB%93/" title="项目回顾 - 实践经验和收获总结">
                        <span class="hidden-mobile">项目回顾 - 实践经验和收获总结</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
  
  
    <article id="comments">
      

    </article>
  


          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header">
    <i class="iconfont icon-list"></i>
    <span>目录</span>
  </p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.fluid-dev.com/docs/guide/" target="_blank" rel="nofollow noopener"> <span>Memory | 个人文档站点</span> </a>
<i class="iconfont icon-love"></i> <a href="https://hexo.fluid-dev.com/docs/guide/" target="_blank" rel="nofollow noopener"> <span>配置指南 | Hexo Fluid 用户手册</span> </a>   
    </div>
  
  
    <div class="statistics">
  
  

  
    
      <span id="leancloud-site-pv-container" style="display: none">
        总访问量 
        <span id="leancloud-site-pv"></span>
         次
      </span>
    
    
      <span id="leancloud-site-uv-container" style="display: none">
        总访客数 
        <span id="leancloud-site-uv"></span>
         人
      </span>
    
    

  
</div>

  
  
    <!-- 备案信息 ICP for China -->
    <div class="beian">
  <span>
    <a href="http://beian.miit.gov.cn/" target="_blank" rel="nofollow noopener">
      京ICP证123456号
    </a>
  </span>
  
    
      <span>
        <a
          href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=12345678"
          rel="nofollow noopener"
          class="beian-police"
          target="_blank"
        >
          
            <span style="visibility: hidden; width: 0">|</span>
            <img src="/memory_blog/img/police_beian.png" alt="police-icon"/>
          
          <span>京公网安备12345678号</span>
        </a>
      </span>
    
  
</div>

  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/memory_blog/js/events.js" ></script>
<script  src="/memory_blog/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>







  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init(Object.assign({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      scrollSmooth    : true,
      includeTitleTags: true,
      headingsOffset  : -boardTop,
    }, CONFIG.toc));
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }

    Fluid.events.registerRefreshCallback(function() {
      if ('tocbot' in window) {
        tocbot.refresh();
        var toc = jQuery('#toc');
        if (toc.length === 0 || !tocbot) {
          return;
        }
        if (toc.find('.toc-list-item').length > 0) {
          toc.css('visibility', 'visible');
        }
      }
    });
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.11/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));

    Fluid.events.registerRefreshCallback(function() {
      if ('anchors' in window) {
        anchors.removeAll();
        var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
        var res = [];
        for (var item of el) {
          res.push('.markdown-body > ' + item.trim());
        }
        if (CONFIG.anchorjs.placement === 'left') {
          anchors.options.class = 'anchorjs-link-left';
        }
        anchors.add(res.join(', '));
      }
    });
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/memory_blog/js/local-search.js" ></script>

  <script defer src="/memory_blog/js/leancloud.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/memory_blog/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
